思路:
- 还是熟悉的递归,像洋葱一样,从外面往里面打印
-
代码:
class Solution:def __init__(self):self.cur_val = 0def externalMatrix(self, matrix: list(list()), left_pos: int, right_pos: int) -> None:if left_pos > right_pos:returnif left_pos == right_pos:self.cur_val += 1matrix[left_pos][right_pos] = self.cur_valfor index in range(left_pos, right_pos):self.cur_val += 1matrix[left_pos][index] = self.cur_valfor index in range(left_pos, right_pos):self.cur_val += 1matrix[index][right_pos] = self.cur_valfor index in range(right_pos, left_pos, -1):self.cur_val += 1matrix[right_pos][index] = self.cur_valfor index in range(right_pos, left_pos, -1):self.cur_val += 1matrix[index][left_pos] = self.cur_valself.externalMatrix(matrix, left_pos + 1, right_pos - 1)def generateMatrix(self, n: int) -> List[List[int]]:matrix = list()for _ in range(n):matrix.append([])for _ in range(n):matrix[-1].append(0)left_pos, right_pos = 0, n - 1self.externalMatrix(matrix, left_pos, right_pos)return matrix
