【每日一题】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(rows===0 || cols===0) return []
const res:number[] = []
let top = 0
let bottom = rows - 1
let left = 0
let right = cols -1
while(left<=right && top<=bottom){
//顶部从左到右
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){
for(let i=right;i>=left;i--){
res.push(matrix[bottom][i])
}
bottom--
}
//左侧从下到上:需要先判断是否已经遍历完所有的列
if(left<=right){
for(let i=bottom;i>=top;i--){
res.push(matrix[i][left])
}
left++
}
}
return res
};
共勉
更多推荐

所有评论(0)