Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.
For example,
Given n = 3
,
[ [ 1, 2, 3 ], [ 8, 9, 4 ], [ 7, 6, 5 ] ]
Subscribe to see which companies asked this question
class Solution(object):
def generateMatrix(self, n):
"""
:type n: int
:rtype: List[List[int]]
"""
self.result = []
for i in range(n):
self.result.append([0]*n)
self.handleMatrix(0,1,n)
return self.result
def handleMatrix(self, start,startnum,n):
if startnum > n**2:
return
for j in range(start, n-start):
self.result[start][j] = startnum
startnum += 1
for i in range(start + 1, n-start):
self.result[i][n - start - 1] = startnum
startnum += 1
for j in range(start, n - start - 1)[::-1]:
self.result[n-start-1][j] = startnum
startnum += 1
for i in range(start + 1, n - start - 1)[::-1]:
self.result[i][start] = startnum
startnum += 1
self.handleMatrix(start + 1,startnum,n)
思路基本与54类似,不再赘述