力扣地址:. - 力扣(LeetCode)
视频讲解:一入循环深似海 | LeetCode:59.螺旋矩阵II_哔哩哔哩_bilibili
文字讲解:代码随想录
记录:这道题其实虽然不好看 但是并不难 最难的在于 x y 比如求顶部 其实是用y的个数来看key为x的值到底有多少
func generateMatrix(n int) [][]int {
startx, starty := 0, 0
var loop int = n / 2
var center int = n / 2
count := 1
offset := 1
res := make([][]int, n)
for i := 0; i < n; i++ {
res[i] = make([]int, n)
}
for loop > 0 {
i, j := startx, starty
//行数不变 列数在变
for j = starty; j < n-offset; j++ {
res[i][j] = count
count++
}
//列数不变是j 行数变
for i = startx; i < n-offset; i++ {
res[i][j] = count
count++
}
//行数不变 i 列数变 j--
for ; j > starty; j-- {
res[i][j] = count
count++
}
//列不变 行变
for ; i > startx; i-- {
res[i][j] = count
count++
}
startx++
starty++
offset++
loop--
}
if n%2 == 1 {
res[center][center] = n * n
}
return res
}