给定一个m x n大小的矩阵(m行,n列),按螺旋的顺序返回矩阵中的所有元素。
要求:空间复杂度 O(nm)O(n**m) ,时间复杂度 O(nm)O(n**m)
-
解法1 ( 按时钟指针转动规则 )
function spiralOrder( matrix ) { if(!matrix.length) return [] // 定义四个指针,并且充当边界限制的作用 let left=0,top=0,right=matrix[0].length-1,bottom=matrix.length-1,res=[] while(top< (matrix.length+1)/2 && left < (matrix[0].length+1)/2 && top<=bottom && left<=right){ /**顶部 从左到右 */ for(let i=left;i<=right;i++){ res.push(matrix[top][i]) } /**右侧 从上到下 */ for(let i=top+1;i<=bottom;i++){ res.push(matrix[i][right]) } /**底部 从右到左 */ for(let i=right-1;top!=bottom&&i>=left;i--){ res.push(matrix[bottom][i]) } /**左侧 从下到上 */ for(let i=bottom-1;left!=right&&i>=top+1;i--){ res.push(matrix[i][top]) } top++ left++ bottom-- right-- } return res }/** 判断数组长度 */ function spiralOrder( matrix ) { if(!matrix.length) return[] const m=matrix[0].length,n=matrix.length let top=0,left=0,right=m-1,bottom=n-1,res=[],num=m*n while(res.length<num){ for(let i=left;i<=right;i++){ res.push(matrix[top][i]) } ++top for(let i=top;i<=bottom;i++){ res.push(matrix[i][right]) } --right if(top>bottom||left>right)break for(let i=right;i>=left;i--){ res.push(matrix[bottom][i]) } --bottom for(let i=bottom;i>=top;i--){ res.push(matrix[i][left]) } left++ } return res } -
解法2 ( 按照圈一圈一圈打印 )
function spiralOrder( matrix ) { let x2=matrix[0].length-1,y2=matrix.length-1,res=[] return circle(matrix,0,0,x2,y2,res) } function circle(matrix,x1,y1,x2,y2,res) { if(x1>x2||y1>y2) return /** 只有一行 */ if(y1==y2){ for(let i=x1;i<=x2;i++){ res.push(matrix[y1][i]) } return } /** 只有一列 */ if(x1==x2){ for(let i=y1;i<=y2;i++){ res.push(matrix[i][x1]) } return } /**顶部 从左到右 */ for(let i=x1;i<=x2;i++){res.push(matrix[y1][i])} /**右侧 从上到下 */ for(let i=y1+1;i<=y2;i++){res.push(matrix[i][x2])} /**底部 从右到左 */ for(let i=x2-1;i>=x1;i--){res.push(matrix[y2][i])} /**左侧 从下到上 */ for(let i=y2-1;i>=y1+1;i--){res.push(matrix[i][x1])} circle(matrix,x1+1,y1+1,x2-1,y2-1,res) return res }\