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 ] ]
跟Spiral Matrix类似,让你把1~n2这些数按螺旋顺序放入矩阵中~做法也是类似的,使用0,1,2,3四个值表示上下左右四个方向以便切换, 用top, bottom, left, right四个变量记录四个边界,复杂度是O(n^2)
class Solution:
# @return a list of lists of integer
def generateMatrix(self, n):
if n <= 0: return []
dir, top, bottom, left, right = 0, 0, n - 1, 0, n - 1
res = [[0 for i in xrange(n)] for j in xrange(n)]; count = 1
while count <= n * n:
if dir == 0:
for i in xrange(left, right + 1):
res[top][i] = count
count += 1
top += 1
elif dir == 1:
for i in xrange(top, bottom + 1):
res[i][right] = count
count += 1
right -= 1
elif dir == 2:
for i in reversed(xrange(left, right + 1)):
res[bottom][i] = count
count += 1
bottom -= 1
else:
for i in reversed(xrange(top, bottom + 1)):
res[i][left] = count
count += 1
left += 1
dir = (dir + 1) % 4
return res