1 问题
给你一个正整数 n ,生成一个包含 1 到 n2 所有元素,且元素按顺时针顺序螺旋排列的 n x n 正方形矩阵 matrix 。
示例 1:
输入:n = 3
输出:[[1,2,3],[8,9,4],[7,6,5]]
示例 2:
输入:n = 1
输出:[[1]]
2 答案
自己写的,参考54.螺旋矩阵
class Solution:def generateMatrix(self, n: int) -> List[List[int]]:matrix = [[0 for _ in range(n)] for _ in range(n)]up, down, left, right = 0, n-1, 0, n-1x, y, cur_d = 0, 0, 0dire = [[0, 1], [1, 0], [0, -1], [-1, 0]]for i in range(n**2):matrix[x][y] = i+1if cur_d == 0 and y == right:cur_d += 1up += 1if cur_d == 1 and x == down:cur_d += 1right -= 1if cur_d == 2 and y == left:cur_d += 1down -= 1if cur_d == 3 and x == up:cur_d += 1left += 1cur_d %= 4x += dire[cur_d][0]y += dire[cur_d][1]return matrix
官方解,循环用的while,方法相似
class Solution(object):def generateMatrix(self, n):if n == 0: return []res = [[0] * n for i in range(n)]left, right, up, down = 0, n - 1, 0, n - 1x, y = 0, 0dirs = [(0, 1), (1, 0), (0, -1), (-1, 0)]cur_d = 0count = 0while count != n * n:res[x][y] = count + 1count += 1if cur_d == 0 and y == right:cur_d += 1up += 1elif cur_d == 1 and x == down:cur_d += 1right -= 1elif cur_d == 2 and y == left:cur_d += 1down -= 1elif cur_d == 3 and x == up:cur_d += 1left += 1cur_d %= 4x += dirs[cur_d][0]y += dirs[cur_d][1]return res
也可以利用坐标是否超过边界来变换遍历方向
class Solution(object):def generateMatrix(self, n):directions = [(0, 1), (1, 0), (0, -1), (-1, 0)]res = [[0] * n for i in range(n)]x, y = 0, 0count = 0cur_d = 0while count != n * n:res[x][y] = count + 1count += 1dx, dy = directions[cur_d][0], directions[cur_d][1]newx, newy = x + dx, y + dy # newx, newy 用于试错,看坐标是否超过边界if newx < 0 or newx >= n or newy < 0 or newy >= n or res[newx][newy] != 0:cur_d = (cur_d + 1) % 4dx, dy = directions[cur_d][0], directions[cur_d][1]x, y = x + dx, y + dyreturn res
https://leetcode.cn/problems/spiral-matrix-ii/solutions/659234/ju-zhen-bian-li-wen-ti-de-si-bu-qu-by-fu-sr5c/