Problem
Given a positive integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.
Example:
Input: 3
Output:
[
[ 1, 2, 3 ],
[ 8, 9, 4 ],
[ 7, 6, 5 ]
]
Solution
解法类似于旋转取值,只不过换成了填值,而且矩阵一定是N×N的,处理起来比较简单
class Solution:
def generateMatrix(self, n: int) -> List[List[int]]:
if n==0:
return []
res = [[0 for _ in range(n)] for _ in range(n)]
left,right,top,floor=0,n-1,0,n-1
num = 1
while left<right or top<floor:
for i in range(left,right):
res[top][i] = num
num += 1
for i in range(top,floor):
res[i][right] = num
num += 1
for i in range(right,left,-1):
res[floor][i] = num
num += 1
for i in range(floor,top,-1):
res[i][left] = num
num += 1
left,right,top,floor=left+1,right-1,top+1,floor-1
if left==right:
res[top][left] = num
return res