leetcode 每日一题 59. 螺旋矩阵 II
模拟
思路:
参考54.螺旋矩阵
代码:
class Solution: def generateMatrix(self, n: int) -> List[List[int]]: res = [[0]*n for _ in range(n)] dc = [1,0,-1,0] dr = [0,1,0,-1] seen = [[False]*n for _ in range(n)] r = c = di = 0 for i in range(n*n): res[r][c] = i+1 seen[r][c] = True cr, cc = r + dr[di], c + dc[di] if 0 <= cr < n and 0 <= cc < n and not seen[cr][cc]: r, c = cr, cc else: di = (di + 1) % 4 r, c = r + dr[di], c + dc[di] return res
按层模拟
思路:
先建一个n*n二维数组,一层一层更新数组的值。
代码:
class Solution: def generateMatrix(self, n: int) -> [[int]]: l, r, t, b = 0, n - 1, 0, n - 1 res = [[0]*n for _ in range(n)] num, tar = 1, n * n while num <= tar: for i in range(l, r + 1): res[t][i] = num num += 1 t += 1 for i in range(t, b + 1): res[i][r] = num num += 1 r -= 1 for i in range(r, l - 1, -1): res[b][i] = num num += 1 b -= 1 for i in range(b, t - 1, -1): res[i][l] = num num += 1 l += 1 return res