原题
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 ]
]
解法
构建n*n的矩阵ans, 初始化值为0, 方向为(右, 下, 左, 上), 使用d来控制方向. 循环n**2次, 每次循环将i加到对应的位置, 并求出下一个位置的(x, y)值, 如果x+dx, y+dy在取值范围内且值为0, 表示可以在该位置赋值, 否则转变方向, 求新的(x,y)值.
Time: O(n2)
Space: O(n2)
代码
class Solution(object):
def generateMatrix(self, n):
"""
:type n: int
:rtype: List[List[int]]
"""
ans = [[0]*n for i in range(n)]
directions = [(0,1), (1,0), (0,-1), (-1,0)]
x, y = 0, 0
d = 0
for i in range(1, n*n+1):
ans[x][y] = i
dx, dy = directions[d]
if 0<= x+dx < n and 0<= y+dy < n and ans[x+dx][y+dy] == 0:
x = x+dx
y = y+dy
else:
d = (d+1)%4
dx, dy = directions[d]
x = x+dx
y = y+dy
return ans