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;
};