0059.螺旋矩阵 II
方法一:模拟
时间复杂度 $O(n^2)$,空间复杂度 $O(1)$。
func generateMatrix(n int) [][]int {
ans := make([][]int, n)
for i := 0; i < n; i++ {
ans[i] = make([]int, n)
}
top, bottom, left, right, v := 0, n-1, 0, n-1, 1
for top <= bottom && left <= right {
for i := left; i <= right; i++ {
ans[top][i], v = v, v+1
}
top += 1
for i := top; i <= bottom; i++ {
ans[i][right], v = v, v+1
}
right -= 1
if top > bottom || left > right {
break
}
for i := right; i >= left; i-- {
ans[bottom][i], v = v, v+1
}
bottom -= 1
for i := bottom; i >= top; i-- {
ans[i][left], v = v, v+1
}
left += 1
}
return ans
}