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 ]
]
这题的解法和spiral matrix1的解法一样,不同的是这个问题的行和列数都一样,所以在算的时候稍微简单一些。
代码如下:
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37class Solution: # @return a list of lists of integer def generateMatrix(self, n): maxup=0 maxleft=0 maxright=n-1 maxdown=n-1 direction=0 matrix=[[0 for i in range(n)] for j in range(n)] num=range(1,n*n+1) iter=0 while True: if direction==0: for i in range(maxleft,maxright+1): matrix[maxup][i]=num[iter] iter+=1 maxup+=1 if direction==1: for i in range(maxup,maxdown+1): matrix[i][maxright]=num[iter] iter+=1 maxright-=1 if direction==2: for i in reversed(range(maxleft,maxright+1)): matrix[maxdown][i]=num[iter] iter+=1 maxdown-=1 if direction==3: for i in reversed(range(maxup,maxdown+1)): matrix[i][maxleft]=num[iter] iter+=1 maxleft+=1 if maxleft>maxright or maxup>maxdown: return matrix direction=(direction+1)%4
最后
以上就是称心香菇最近收集整理的关于59. Spiral Matrix II Leetcode Python的全部内容,更多相关59.内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复