54. Spiral Matrix
Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.
Example 1:
Input: [ [ 1, 2, 3 ], [ 4, 5, 6 ], [ 7, 8, 9 ] ] Output: [1,2,3,6,9,8,7,4,5]
Example 2:
Input: [ [1, 2, 3, 4], [5, 6, 7, 8], [9,10,11,12] ] Output: [1,2,3,4,8,12,11,10,9,5,6,7]
题意:将二维数组顺时针螺旋输出为一维数组
代码如下:
/** * @param {number[][]} matrix * @return {number[]} */ var spiralOrder = function(matrix) { if(matrix.length==0){ return matrix; } var rowLen=matrix.length; var colLen=matrix[0].length; var left=0,right=colLen,up=0,down=rowLen;//上下左右四个方向遍历 var i=0; var res=[]; while(i<rowLen*colLen){ //从左向右遍历 for(var j=left;j<right;j++){ if(i>=rowLen*colLen) break; res.push(matrix[up][j]) i++; } up++; //从上向下遍历 for(var j=up;j<down;j++){ if(i>=rowLen*colLen) break; res.push(matrix[j][right-1]) i++; } right--; //从右向左遍历 for(var j=right-1;j>=left;j--){ if(i>=rowLen*colLen) break; res.push(matrix[down-1][j]); i++; } down--; //从下向上 for(var j=down-1;j>=up;j--){ if(i>=rowLen*colLen) break; res.push(matrix[j][left]) i++; } left++; } return res };