54.螺旋矩阵
题目:给定一个m x n大小的矩阵(m行,n列),按螺旋的顺序返回矩阵中的所有元素
提示:
m == matrix.length
n == matrix[i].length
1 <= m, n <= 10
-100 <= matrix[i][j] <= 100
代码:
1 /** 2 * 3 * @param matrix int整型二维数组 4 * @return int整型一维数组 5 */ 6 function spiralOrder( matrix ) { 7 // write code here 8 if(matrix.length === 0){ 9 return []; 10 } 11 let top = 0; 12 let bottom = matrix.length-1; 13 let left = 0; 14 let right = matrix[0].length - 1; 15 16 let direction = "right"; 17 let result = []; 18 while(left <= right && top <= bottom){ 19 if(direction === "right"){ 20 for(let i = left;i <= right;i++){ 21 result.push(matrix[top][i]); 22 } 23 top++; 24 direction = "down"; 25 }else if(direction === "down"){ 26 for(let i = top; i <= bottom;i++){ 27 result.push(matrix[i][right]); 28 } 29 right--; 30 direction = "left"; 31 }else if(direction === "left"){ 32 for(let i = right;i >= left;i--){ 33 result.push(matrix[bottom][i]); 34 } 35 bottom--; 36 direction = "top"; 37 }else if(direction === "top"){ 38 for(let i = bottom; i>= top;i--){ 39 result.push(matrix[i][left]); 40 } 41 left++; 42 direction = "right"; 43 } 44 } 45 return result; 46 } 47 module.exports = { 48 spiralOrder : spiralOrder 49 };

浙公网安备 33010602011771号