Golang | Leetcode Golang题解之第59题螺旋矩阵II

题目:

题解:

Go 复制代码
func generateMatrix(n int) [][]int {
    matrix := make([][]int, n)
    for i := range matrix {
        matrix[i] = make([]int, n)
    }
    num := 1
    left, right, top, bottom := 0, n-1, 0, n-1
    for left <= right && top <= bottom {
        for column := left; column <= right; column++ {
            matrix[top][column] = num
            num++
        }
        for row := top + 1; row <= bottom; row++ {
            matrix[row][right] = num
            num++
        }
        if left < right && top < bottom {
            for column := right - 1; column > left; column-- {
                matrix[bottom][column] = num
                num++
            }
            for row := bottom; row > top; row-- {
                matrix[row][left] = num
                num++
            }
        }
        left++
        right--
        top++
        bottom--
    }
    return matrix
}
相关推荐
鹿角片ljp3 小时前
LeetCode 46. 全排列|吃透回溯
算法·leetcode·职场和发展
剩下了什么3 小时前
float32 与 float64 精度陷阱:如何在 Go 中避免错误使用
开发语言·后端·golang
.道阻且长.5 小时前
11.LeetCode算法习题讲解--滑动窗口--将x减到0的最小操作数
算法·leetcode·职场和发展
wenyq76 小时前
LeetCode 2460. Apply Operations to an Array
算法·leetcode
青 春 记 忆7 小时前
LeetCode 142. 环形链表 II|Python 解法详解
python·leetcode·链表
小欣加油7 小时前
leetcode3069 将元素分配到两个数组中I
数据结构·c++·算法·leetcode·职场和发展
ttwuai9 小时前
Go 后台接入 SSO 后菜单正常但接口 403,怎么排查权限链路?
开发语言·后端·golang
PC2005-cloud9 小时前
Go学习笔记:基本概念与项目结构——GOPATH、Go Modules 与常用命令
笔记·学习·golang
ttwuai10 小时前
Go 后台图片上传到对象存储后,预览 403/404 怎么排查?
开发语言·golang
nike0good10 小时前
April Fools Day Contest 2026 题解
算法·题解·愚人节比赛