Spiral Matrix
来源:互联网 发布:p2p种子搜索器mac版 编辑:程序博客网 时间:2024/06/06 11:42
Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.
For example,
Given the following matrix:
[ [ 1, 2, 3 ], [ 4, 5, 6 ], [ 7, 8, 9 ]]
You should return [1,2,3,6,9,8,7,4,5]
.
思路:这是个m,n矩阵,每次绕着外围扫一圈,扫到剩下的最后一个 [ x ], [x, y, z], [ x ], [ y ]
那么定义宽和高,可得到四个角。扫完第一行,heightStart+1,扫完最右边一列,widthEnd-1。
由于heightStart加了一,check是否已经是最底下一行。
var spiralOrder = function(matrix) { var result = []; var n = matrix.length; var m = (matrix.length===0? 0:matrix[0].length); var widthStart = 0, widthEnd = m-1, heightStart = 0, heightEnd = n-1; while (widthStart<=widthEnd&&heightStart<=heightEnd) { for (var i=widthStart;i<=widthEnd;i++) { result.push(matrix[heightStart][i]); } heightStart++ for (var j=heightStart;j<=heightEnd;j++) { result.push(matrix[j][widthEnd]); } widthEnd-- if (heightStart<=heightEnd) { for (var k=widthEnd;k>=widthStart;k--) { result.push(matrix[heightEnd][k]); } heightEnd-- } if (widthStart<=widthEnd) { for (var x=heightEnd;x>=heightStart;x--) { result.push(matrix[x][widthStart]) } widthStart++ } } return result;};
0 0
- Spiral Matrix
- Spiral Matrix
- Spiral Matrix
- Spiral Matrix
- Spiral Matrix
- Spiral Matrix
- Spiral Matrix
- Spiral Matrix
- Spiral Matrix
- Spiral Matrix
- Spiral Matrix
- Spiral Matrix
- Spiral Matrix
- Spiral Matrix
- Spiral Matrix
- Spiral Matrix
- Spiral Matrix
- Spiral Matrix
- Unity5的AssetBundle的一点使用心得
- iOS中dismissViewController实现多级模态跳转
- JAVA之多线程yield(),sleep(),wait()区别
- js focus输入焦点和判断邮件地址是否有@
- WMI Backdoor
- Spiral Matrix
- oracle 11g 下载地址
- android 文件关联 mimeType
- Android应用程序安装原理小结
- 实现一个复杂的悬浮窗
- xcode6 下 ios simulator 有 Home 键
- opencv:批量读取一个文件夹下的图片,并转换成视频
- 设计模式文章(一)
- 【iOS】UIFont字体样式设置