原题链接
https://leetcode.com/problems/spiral-matrix-ii
解题思路
用round记录当前处于第几轮,按照上右下左的顺序不断转圈输出即可。但需要注意的是当上下重合为一行时需要判断一下,中止程序。
代码
class Solution(object):
def generateMatrix(self, n):
"""
:type n: int
:rtype: List[List[int]]
"""
matrix = [[0 for i in range(n)] for j in range(n)]
round = 0
index = 1
# fill the first row
while round<n//2+1:
for col in range(round, n-round):
matrix[round][col] = index
index += 1
for row in range(round+1, n-1-round):
matrix[row][n-1-round] = index
index += 1
if n-1-round==round:
break
for col in range(n-round-1,round-1,-1):
matrix[n-1-round][col] = index
index += 1
for row in range(n-2-round, round, -1):
matrix[row][round] = index
index += 1
round += 1
return matrix
参考链接
https://blog.csdn.net/nerv3x3/article/details/41628823