59. Spiral Matrix II Leetcode Python
来源:互联网 发布:淘宝详情页图片模板 编辑:程序博客网 时间:2024/05/02 01:59
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 ]
For example,
Given n = 3,
You should return the following matrix:
[
[ 1, 2, 3 ],
[ 8, 9, 4 ],
[ 7, 6, 5 ]
]
这题的解法和spiral matrix1的解法一样,不同的是这个问题的行和列数都一样,所以在算的时候稍微简单一些。
代码如下:
class 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
0 0
- 【Leetcode】【python】Spiral Matrix/Spiral Matrix II
- 59. Spiral Matrix II Leetcode Python
- LeetCode 59. Spiral Matrix II(Python)
- [LeetCode]59.Spiral Matrix II
- LeetCode --- 59. Spiral Matrix II
- [Leetcode] 59. Spiral Matrix II
- [leetcode] 59.Spiral Matrix II
- LeetCode 59. Spiral Matrix II
- 59. Spiral Matrix II LeetCode
- [leetcode] 59. Spiral Matrix II
- leetcode 59. Spiral Matrix II
- LeetCode 59. Spiral Matrix II
- leetcode 59. Spiral Matrix II
- LeetCode *** 59. Spiral Matrix II
- leetcode 59. Spiral Matrix II
- Leetcode 59. Spiral Matrix II
- LeetCode 59. Spiral Matrix II
- LeetCode - 59. Spiral Matrix II
- 深圳南湾刨花板厂有几家呢
- Android sqlite db-journal文件的产生和原因
- 沙井刨花板哪家质量好呢
- Ucinet学习笔记一:DL Input
- 题目1 : 最短路径·三:SPFA算法
- 59. Spiral Matrix II Leetcode Python
- hdu 1158 简单dp
- 利用C/C++扩展php语言实现 Usher_GetHostIP无参函数
- 入门训练 序列求和
- 10-2. 删除字符串中的子串(20)
- 【C++】OJ提交题目中的语言选项里G++与C++的区别
- LightOJ - 1174 Commandos
- IOS中点语法的变态用法(我叫做不法用法)
- uva 1346(贪心)