解题思路
在矩阵四周添加一圈障碍物
后续在碰到障碍物的时候调整方向
总共处理N * N个元素后停止
59. 螺旋矩阵 II
代码
class Solution:
def generateMatrix(self, n: int) -> List[List[int]]:
matrix = [[None for _ in range(n)][:] for _ in range(n)]
obstacle = set()
for r in range(n):
obstacle.add((r, -1)) # 每一行的开头加一个障碍物
obstacle.add((r, n)) # 每一行的结尾加一个障碍物
obstacle.add((-1, r)) # 每一列的开头加一个障碍物
obstacle.add((n, r)) # 每一列的结尾加一个障碍物
direction = [(0, 1), (1, 0), (0, -1), (-1, 0)]
count, total = 1, n * n
di = 0
x, y = 0, 0
while count <= total:
matrix[x][y] = count
obstacle.add((x, y))
next_x = x+direction[di][0]
next_y = y+direction[di][1]
if (next_x, next_y) in obstacle:
di = (di+1) % 4
x, y = x+direction[di][0], y+direction[di][1]
count += 1
return matrix
效果图
网友评论