原题
https://leetcode.cn/problems/spiral-matrix-ii/description/
思路
遍历
复杂度
时间:O(n * n)
空间:O(n * n)
Python代码
class Solution:
def generateMatrix(self, n: int) -> List[List[int]]:
ans = [[0] * n for i in range(n)]
# 坐标
i, j = 0, 0
# 方向
d = 0
directions = [(0, 1), (1, 0), (0, -1), (-1, 0)]
num = 1
while num <= n * n:
ans[i][j] = num
num += 1
# 确定方向
di, dj = directions[d]
# 下一步在数组内且没走过
if 0 <= i + di < n and 0 <= j + dj < n and ans[i+di][j + dj] == 0:
i += di
j += dj
# 换方向
else:
d = (d + 1) % 4
di, dj = directions[d]
i += di
j += dj
return ans
Go代码
func generateMatrix(n int) [][]int {
// 构建二维切片
ans := make([][]int, n)
for i := range ans {
ans[i] = make([]int, n)
}
// 坐标
i, j := 0, 0
// 方向
d := 0
directions := [][]int{{0, 1}, {1, 0}, {0, -1}, {-1, 0}}
num := 1
for num <= n*n {
ans[i][j] = num
num++
// 确定方向
di, dj := directions[d][0], directions[d][1]
// 下一步在数组内且没走过
if 0 <= i+di && i+di < n && 0 <= j+dj && j+dj < n && ans[i+di][j+dj] == 0 {
i += di
j += dj
} else {
d = (d + 1) % 4
di, dj = directions[d][0], directions[d][1]
i += di
j += dj
}
}
return ans
}
470

被折叠的 条评论
为什么被折叠?



