思路:
- 还是熟悉的递归,像洋葱一样,从外面往里面打印
-
代码:
class Solution:
def __init__(self):
self.cur_val = 0
def externalMatrix(self, matrix: list(list()), left_pos: int, right_pos: int) -> None:
if left_pos > right_pos:
return
if left_pos == right_pos:
self.cur_val += 1
matrix[left_pos][right_pos] = self.cur_val
for index in range(left_pos, right_pos):
self.cur_val += 1
matrix[left_pos][index] = self.cur_val
for index in range(left_pos, right_pos):
self.cur_val += 1
matrix[index][right_pos] = self.cur_val
for index in range(right_pos, left_pos, -1):
self.cur_val += 1
matrix[right_pos][index] = self.cur_val
for index in range(right_pos, left_pos, -1):
self.cur_val += 1
matrix[index][left_pos] = self.cur_val
self.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 - 1
self.externalMatrix(matrix, left_pos, right_pos)
return matrix