59. 螺旋矩阵 II

59. 螺旋矩阵 II

给你一个正整数 n ,生成一个包含 1n2 所有元素,且元素按顺时针顺序螺旋排列的 n x n 正方形矩阵 matrix
示例 1:
59. 螺旋矩阵 II - 图1

  1. 输入:n = 3
  2. 输出:[[1,2,3],[8,9,4],[7,6,5]]

示例 2:

  1. 输入:n = 1
  2. 输出:[[1]]

提示:

  • 1 <= n <= 20

题解

说实话,和昨天的每日一题 54. 螺旋矩阵 几乎没有区别,又水了一题,美滋滋

  1. class Solution:
  2. def generateMatrix(self, n):
  3. matrix=[[0]*n for _ in range(n)]
  4. dd = [[0, 1], [1, 0], [0, -1], [-1, 0]]
  5. w_h = [n, n-1]
  6. x, y = (0, -1)
  7. i = 1
  8. direct = 0
  9. while i <= n*n:
  10. for _ in range(w_h[direct % 2]):
  11. x, y = (x+dd[direct][0], y+dd[direct][1])
  12. # print(x,y)
  13. # print(matrix[x][y])
  14. matrix[x][y]=i
  15. i += 1
  16. w_h[direct % 2] -= 1
  17. direct = (direct+1) % 4
  18. return matrix