- 分类:Array
- 时间复杂度: O(n*m)
59. Spiral Matrix II
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 ]
]
代码:
方法:
class Solution:
def generateMatrix(self, n: 'int') -> 'List[List[int]]':
if n==0:
return [[]]
matrix=[[0 for i in range(n)] for i in range(n)]
num=1
top,left,row,col=0,0,0,0
right,bottom=n-1,n-1
while top<bottom and left<right:
while col<right:
matrix[row][col]=num
col+=1
num+=1
while row<bottom:
matrix[row][col]=num
row+=1
num+=1
while col>left:
matrix[row][col]=num
col-=1
num+=1
while row>top:
matrix[row][col]=num
row-=1
num+=1
top+=1
left+=1
col+=1
row+=1
bottom-=1
right-=1
if top==bottom and left==right:
matrix[top][left]=num
return matrix
讨论:
1.谨记四个角的坐标不要写错了。。。