LeetCode笔记:螺旋矩阵
问题
给你一个 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.length
n == matrix[i].length
1 <= m, n <= 10
-100 <= matrix[i][j] <= 100
解法
思路:
- 设定上下左右的开始和结束位置变量
- 按照要求横向遍历和竖向遍历,每次遍历完一个方向,则缩小开始结束位置,即可达到螺旋的效果
代码:
/**
* @param {number[][]} matrix
* @return {number[]}
*/
var spiralOrder = function (matrix) {
// 为空判断
if (matrix.length === 0) return [];
// 存储结果数组
const result = [];
// 获取初始的元素位置信息
let left = 0,
right = matrix[0].length - 1,
top = 0,
bottom = matrix.length - 1;
while (true) {
// 向右遍历
for (let i = left; i <= right; i++) {
result.push(matrix[top][i]);
}
// 遍历结束,刚刚遍历过的top值不再使用,上边界需要+1往下移动,如果top值超过了bottom值,说明竖向遍历已经结束了,退出循环
if (++top > bottom) break;
// 向下遍历
for (let i = top; i <= bottom; i++) {
result.push(matrix[i][right]);
}
// 遍历结束,刚刚遍历过的right值不再使用,右边界需要-1往左移动,如果right值小于left值,说明横向遍历已经结束了,退出循环
if (--right < left) break;
// 向左遍历
for (let i = right; i >= left; i--) {
result.push(matrix[bottom][i]);
}
// 遍历结束,刚刚遍历过的bottom值不再使用,下边界需要-1往上移动,如果bottom值小于top值,说明竖向遍历已经结束了,退出循环
if (--bottom < top) break;
// 向上遍历
for (let i = bottom; i >= top; i--) {
result.push(matrix[i][left]);
}
// 遍历结束,刚刚遍历过的left值不再使用,左边界需要+1往右移动,如果left值大于right值,说明横向遍历已经结束了,退出循环
if (++left > right) break;
}
return result;
};
评论