题目:
给定一个正整数 n,生成一个包含 1 到 n2 所有元素,且元素按顺时针顺序螺旋排列的正方形矩阵。
思路:
是第54题的逆向过程
程序:
class Solution:
def generateMatrix(self, n: int) -> List[List[int]]:
if n <= 0:
return []
if n == 1:
return [[1]]
matrix = [[0 for i in range(n)] for i in range(n)]
row_begin = 0
row_end = n - 1
column_begin = 0
column_end = n - 1
number = 1
while row_begin <= row_end and column_begin <= column_end and number <= n * n:
for index1 in range(column_begin, column_end + 1):
matrix[row_begin][index1] = number
number += 1
row_begin += 1
for index2 in range(row_begin, row_end + 1):
matrix[index2][column_end] = number
number += 1
column_end -= 1
for index1 in range(column_end, column_begin - 1, -1):
if row_end >= row_begin:
matrix[row_end][index1] = number
number += 1
row_end -= 1
for index2 in range(row_end, row_begin - 1, -1):
if column_end >= column_begin:
matrix[index2][column_begin] = number
number += 1
column_begin += 1
return matrix