题目
解法
这道题目其实跟这道https://blog.csdn.net/qq_37821701/article/details/112093118一模一样。参考这道题目里面的第二种解法
class Solution:
def generateMatrix(self, n: int) -> List[List[int]]:
cnt = 1
dirs = [[0,1],[1,0],[0,-1],[-1,0]]
row = 0
col = -1
d_ind = 0
seen = set()
res = [[0] * n for _ in range(n)]
while cnt < n*n + 1:
x = row + dirs[d_ind][0]
y = col + dirs[d_ind][1]
if x >= 0 and x < n and y >= 0 and y < n and (x,y) not in seen:
res[x][y] = cnt
row = x
col = y
cnt += 1
seen.add((x,y))
else:
d_ind = (d_ind+1) % len(dirs)
return res