【每日一题】LeetCode 54. 螺旋矩阵 TypeScript
给你一个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.lengthn matrix[i].length1 m, n 10-100 matrix[i][j] 100核心思路1.顶部从左到右开始遍历2.右侧从上到下开始遍历3.判断还有没有行底部从右到左开始遍历4.判断还有没有列左侧从下到上开始遍历function spiralOrder(matrix: number[][]): number[] { const rows matrix.length const cols matrix[0].length if(rows0 || cols0) return [] const res:number[] [] let top 0 let bottom rows - 1 let left 0 let right cols -1 while(leftright topbottom){ //顶部从左到右 for(let ileft;iright;i){ res.push(matrix[top][i]) } top //右侧从上到下 for(let itop;ibottom;i){ res.push(matrix[i][right]) } right-- //底部从右到左需要判断是否还有行没有遍历完 if(topbottom){ for(let iright;ileft;i--){ res.push(matrix[bottom][i]) } bottom-- } //左侧从下到上需要先判断是否已经遍历完所有的列 if(leftright){ for(let ibottom;itop;i--){ res.push(matrix[i][left]) } left } } return res };共勉