Question
Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.
For example,
Given n = 3,
You should return the following matrix:
[
[ 1, 2, 3 ],
[ 8, 9, 4 ],
[ 7, 6, 5 ]
]
Hide Tags Array
Hide Similar Problems (M) Spiral Matrix
Solution
class Solution(object):
def generateMatrix(self, n):
"""
:type n: int
:rtype: List[List[int]]
"""
if n==0:
return []
total = n**2
res = [[0]*n for dummy in range(n)]
levelnum = n / 2
i = 1
for level in range(levelnum):
for ind in range(level, n-level-1):
res[level][ind] = i
i += 1
for ind in range(level, n-level-1):
res[ind][n-1-level] = i
i += 1
for ind in range(n-1-level, level, -1):
res[n-1-level][ind] = i
i += 1
for ind in range(n-1-level, level, -1):
res[ind][level] = i
i += 1
if n%2==1:
res[n/2][n/2] = i
return res