class Solution(object):
def generateMatrix(self, n):
"""
:type n: int
:rtype: List[List[int]]
"""
if n==0:return []
d=[[0,1],[1,0],[0,-1],[-1,0]]
ans=[[0 for x in range(n)]for y in range(n)]
x=0
y=0
direction=0
num=1
ans[0][0]=num
for i in range(1,n*n):
while(True):
newx=x+d[direction][0]
newy=y+d[direction][1]
if newx>=0 and newx<n and newy>=0 and newy<n and ans[newx][newy]==0:
num+=1
ans[newx][newy]=num
x=newx
y=newy
break
else:
direction=(direction+1)%4
return ansLeetCode-59-Spiral Matrix II 模拟水题
最新推荐文章于 2025-08-02 22:44:27 发布
本文介绍了一个使用Python实现的螺旋矩阵生成算法。该算法通过定义方向数组来控制填充数字的方向,并根据边界条件动态调整填充路径,最终生成指定大小的螺旋矩阵。
1906

被折叠的 条评论
为什么被折叠?



