spiral_matrix.py 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. from typing import List
  2. class Solution:
  3. def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
  4. m, n = len(matrix), len(matrix[0])
  5. tar = m * n
  6. visit = set()
  7. res = []
  8. x, y = 0, -1
  9. dx, dy = 0, 1
  10. for num in range(tar):
  11. x, y = x + dx, y + dy
  12. res.append(matrix[x][y])
  13. visit.add((x, y))
  14. dx, dy = self.coor((x, y), (dx, dy), visit, m, n)
  15. return res
  16. def coor(self, coord, direct, visit, m, n):
  17. x, y = coord
  18. dx, dy = direct
  19. if dx == 0 and dy == 1:
  20. if y == n - 1 or (x, y + 1) in visit:
  21. return (1, 0)
  22. if dx == 1 and dy == 0:
  23. if x == m - 1 or (x + 1, y) in visit:
  24. return (0, -1)
  25. if dx == 0 and dy == -1:
  26. if y == 0 or (x, y - 1) in visit:
  27. return (-1, 0)
  28. if dx == -1 and dy == 0:
  29. if (x - 1, y) in visit:
  30. return (0, 1)
  31. return (dx, dy)
  32. if __name__ == "__main__":
  33. s = Solution()
  34. a = s.spiralOrder([[1,2,3,4],[5,6,7,8],[9,10,11,12]])
  35. print(a)