spiral_matrix_II.py 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. from typing import List
  2. # def generateMatrix(n: int) -> List[List[int]]:
  3. # 法一
  4. # l, r, t, b = 0, n - 1, 0, n - 1
  5. # res = [[0 for _ in range(n)] for _ in range(n)]
  6. # num, tar = 1, n * n
  7. # while num <= tar:
  8. # for i in range(l, r + 1): # left to right
  9. # res[t][i] = num
  10. # num += 1
  11. # t += 1
  12. # for i in range(t, b + 1): # top to bottom
  13. # res[i][r] = num
  14. # num += 1
  15. # r -= 1
  16. # for i in range(r, l - 1, -1): # right to left
  17. # res[b][i] = num
  18. # num += 1
  19. # b -= 1
  20. # for i in range(b, t - 1, -1): # bottom to top
  21. # res[i][l] = num
  22. # num += 1
  23. # l += 1
  24. # return res
  25. # 法二
  26. class Solution:
  27. def generateMatrix(self, n: int) -> List[List[int]]:
  28. tar = n * n
  29. visit = set()
  30. x, y = 0, -1
  31. dx, dy = 0, 1
  32. res = [[0 for _ in range(n)] for _ in range(n)]
  33. for num in range(tar):
  34. x, y = x + dx, y + dy
  35. visit.add((x, y))
  36. res[x][y] = num + 1
  37. dx, dy = self.coor((x, y), (dx, dy), visit, n)
  38. return res
  39. def coor(self, coord, direct, visit, n):
  40. x, y = coord
  41. dx, dy = direct
  42. if dx == 0 and dy == 1:
  43. if y == n - 1 or (x, y + 1) in visit:
  44. return (1, 0)
  45. if dx == 1 and dy == 0:
  46. if x == n - 1 or (x + 1, y) in visit:
  47. return (0, -1)
  48. if dx == 0 and dy == -1:
  49. if y == 0 or (x, y - 1) in visit:
  50. return (-1, 0)
  51. if dx == -1 and dy == 0:
  52. if (x - 1, y) in visit:
  53. return (0, 1)
  54. return (dx, dy)