image.png

思路:

  • 还是熟悉的递归,像洋葱一样,从外面往里面打印
  • 需要一开始初始化合适的数组大小

    代码:

    1. class Solution:
    2. def __init__(self):
    3. self.cur_val = 0
    4. def externalMatrix(self, matrix: list(list()), left_pos: int, right_pos: int) -> None:
    5. if left_pos > right_pos:
    6. return
    7. if left_pos == right_pos:
    8. self.cur_val += 1
    9. matrix[left_pos][right_pos] = self.cur_val
    10. for index in range(left_pos, right_pos):
    11. self.cur_val += 1
    12. matrix[left_pos][index] = self.cur_val
    13. for index in range(left_pos, right_pos):
    14. self.cur_val += 1
    15. matrix[index][right_pos] = self.cur_val
    16. for index in range(right_pos, left_pos, -1):
    17. self.cur_val += 1
    18. matrix[right_pos][index] = self.cur_val
    19. for index in range(right_pos, left_pos, -1):
    20. self.cur_val += 1
    21. matrix[index][left_pos] = self.cur_val
    22. self.externalMatrix(matrix, left_pos + 1, right_pos - 1)
    23. def generateMatrix(self, n: int) -> List[List[int]]:
    24. matrix = list()
    25. for _ in range(n):
    26. matrix.append([])
    27. for _ in range(n):
    28. matrix[-1].append(0)
    29. left_pos, right_pos = 0, n - 1
    30. self.externalMatrix(matrix, left_pos, right_pos)
    31. return matrix