1. 题目描述
给定一个包含 m x n 个元素的矩阵(m 行, n 列),请按照顺时针螺旋顺序,返回矩阵中的所有元素。
示例 1:
输入:
[
[ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ]
]
输出: [1,2,3,6,9,8,7,4,5]
示例 2:
输入:
[
[1, 2, 3, 4],
[5, 6, 7, 8],
[9,10,11,12]
]
输出: [1,2,3,4,8,12,11,10,9,5,6,7]
2. 解题思路
对于这道题目,我们可以这样对二维数组进行遍历:
在每一行每一列遍历的时候,不遍历到头,这样形成了一个个圆环,并且可以减少横向和竖向遍历之间的影响,经过一轮遍历之后,就四个边界都进行缩窄1,这样就可以往内部进行不断循环。
这里定义了四个边界:
- 上边界 top : 0
- 下边界 bottom : matrix.length - 1
- 左边界 left : 0
- 右边界 right : matrix[0].length - 1
需要注意的是,最后有可能剩余一行或者一列,它是无法构成圆环的,这种情况就要单独的处理:
- 剩一行的情况:
top == bottom && left < right
- 剩一列的情况:
top < bottom && left == right
- 剩一项(也是一行/列)的情况:
top == bottom && left == right
复杂度分析:
- 时间复杂度:O(m*n),其中m、n 分别是矩阵的行数和列数,矩阵的每一个元素都要被访问一次。
-
3. 代码实现
/**
* @param {number[][]} matrix
* @return {number[]}
*/
var spiralOrder = function(matrix) {
if(!matrix.length) {
return []
}
let top = 0, bottom = matrix.length - 1, left = 0, right = matrix[0].length - 1
const res = []
while(top < bottom && left < right){
for(let i = left; i < right; i++) res.push(matrix[top][i])
for(let i = top; i < bottom; i++) res.push(matrix[i][right])
for(let i = right; i > left; i--) res.push(matrix[bottom][i])
for(let i = bottom; i > top; i--) res.push(matrix[i][left])
right--
top++
bottom--
left++
}
if(bottom === top){ // 剩下一行的情况
for(let i = left; i <= right; i++){
res.push(matrix[top][i])
}
}else if(left === right){ // 剩下一列的情况
for(let i = top; i <= bottom; i++){
res.push(matrix[i][left])
}
}
return res
};
4. 提交结果