【LEETCODE】59-Spiral Matrix II
2016-01-06 17:08
661 查看
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 ]
]
题意:
给一个整数 n,生成一个方阵,由 1 到 n^2 的螺旋顺序构成
参考: http://www.cnblogs.com/zuoyuan/p/3769892.html
思路:
用count去在该有的位置填入该有的数字,当count满足n*n时则返回最终结果
用 up right down left 分别去当四条边的指针,填满一条边后进行更新
direct 是除4的余数,用来控制目前应该填入哪条边了
n2 in spiral order.
For example,
Given n = 3,
You should return the following matrix:
[
[ 1, 2, 3 ],
[ 8, 9, 4 ],
[ 7, 6, 5 ]
]
题意:
给一个整数 n,生成一个方阵,由 1 到 n^2 的螺旋顺序构成
参考: http://www.cnblogs.com/zuoyuan/p/3769892.html
思路:
用count去在该有的位置填入该有的数字,当count满足n*n时则返回最终结果
用 up right down left 分别去当四条边的指针,填满一条边后进行更新
direct 是除4的余数,用来控制目前应该填入哪条边了
class Solution(object): def generateMatrix(self, n): """ :type n: int :rtype: List[List[int]] """ if n==0: return [] matrix=[[n for i in range(n)]for j in range(n)] left=0 up=0 right=n-1 down=n-1 direct=0 count=0 while True: if direct==0: #此时为 上边 for i in range(left,right+1): #up控制上边 当前的行,left为当前起点,right为终点 count+=1 matrix[up][i]=count up+=1 #写完一行,要进行更新 if direct==1: #右边 for i in range(up,down+1): count+=1 matrix[i][right]=count right-=1 if direct==2: #下边 for i in range(right,left-1,-1): count+=1 matrix[down][i]=count down-=1 if direct==3: #左边 for i in range(down,up-1,-1): count+=1 matrix[i][left]=count left+=1 if count==n*n: #终止条件 return matrix direct=(direct+1)%4 #更新边的方向
相关文章推荐
- 使用CocoaPods 删除已经配置的类库和移除CocoaPods
- leetcode第11题——**Container With Most Water
- 找不到符号
- 错误 341 “sgen.exe”已退出,代码为 1
- OpenGL显示列表
- UITableView中visibleCells方法的使用
- 使用float和clear创建网站三栏液态布局
- Net Memory Profiler 分析.Net程序内存泄露
- javascript严格模式
- android-support-v7-appcompat
- 产品、运营、研发之间
- Linux进程间通信方式
- React 入门实例教程
- React 入门实例教程
- 结合源码分析android的消息机制
- CODE[VS]1215 迷宫
- jbpm应用开发
- android调用摄像头拍照并显示
- Halcon学习备忘六(拟合圆的一种方法)
- echarts绘制四川地图