54. 螺旋矩阵
给你一个 m
行 n
列的矩阵 matrix
,请按照 顺时针螺旋顺序 ,返回矩阵中的所有元素。
示例 1:
输入:matrix = [[1,2,3],[4,5,6],[7,8,9]]
输出:[1,2,3,6,9,8,7,4,5]
示例 2:
输入:matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]
输出:[1,2,3,4,8,12,11,10,9,5,6,7]
提示:
m == matrix.length
n == matrix[i].length
1 <= m, n <= 10
-100 <= matrix[i][j] <= 100
/**
* @param {number[][]} matrix
* @return {number[]}
*/
var spiralOrder = function(matrix) {
let index = 1;
let len = matrix.length*matrix[0].length;
let v = 0;
let i=0,j=0;
let result = [];
let right = matrix[0].length-1;
let left = 0 ;
let top = 1;
result.push(matrix[0][0])
let bottom = matrix.length-1;
while(index!=len){
// console.log(i,j, v, result)
if(v==0){
j++;
if(j>right){
v = 1;
right--;
j--;
continue;
}
result.push(matrix[i][j]);
}else if(v==1){
i++;
if(i>bottom){
bottom--;
v = 2;
i--;
continue;
}
result.push(matrix[i][j]);
}else if(v==2){
j--;
if(j<left){
v = 3;
left++;
j++;
continue;
}
result.push(matrix[i][j]);
}else if(v==3){
i--;
if(i<top){
v= 0;
top++;
i++;
continue;
}
result.push(matrix[i][j]);
}
index++;
}
// console.log(index, len, result.length)
return result;
};