✅54. 螺旋矩阵
Opened this issue · 2 comments
bazinga-web commented
给定一个包含 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]
bazinga-web commented
解题思路:
- 如果数组为空,则返回空数组
- 定义四个边界及当前方向
- 当左边界小于等于右边界,且上边界小于等于下边界时,
执行while循环:按照右下左上的顺序,依次将经过的
字符添加到结果中 - while循环结束返回结果
/**
* @param {number[][]} matrix
* @return {number[]}
*/
var spiralOrder = function (matrix) {
let result = [];
if (matrix.length === 0) return result;
let left = 0,
right = matrix[0].length - 1,
top = 0,
bottom = matrix.length - 1,
direction = "right";
while (left <= right && top <= bottom) {
if (direction === "right") {
for (let i = left; i <= right; i++) {
result.push(matrix[top][i]);
}
top++;
direction = "down";
} else if (direction === "down") {
for (let i = top; i <= bottom; i++) {
result.push(matrix[i][right]);
}
right--;
direction = "left";
} else if (direction === "left") {
for (let i = right; i >= left; i--) {
result.push(matrix[bottom][i]);
}
bottom--;
direction = "top";
} else if (direction === "top") {
for (let i = bottom; i >= top; i--) {
result.push(matrix[i][left]);
}
left++;
direction = "right";
}
}
return result;
};
Ray-56 commented
方向遍历解
/**
* @param {number[][]} matrix
* @return {number[]}
*/
var spiralOrder = function(matrix) {
if (!matrix.length) return [];
let ret = [];
let top = 0;
let bottom = matrix.length - 1;
let left = 0;
let right = matrix[0].length - 1;
let direction = 'right';
while (left <= right && top <= bottom) {
if (direction == 'right') {
for (let i = left ; i <= right; i++) {
ret.push(matrix[top][i]);
}
direction = 'bottom';
top++;
} else if (direction == 'bottom') {
for (let i = top; i <= bottom; i++) {
ret.push(matrix[i][right]);
}
direction = 'left';
right--;
} else if (direction == 'left') {
for (let i = right; i >= left; i--) {
ret.push(matrix[bottom][i]);
}
direction = 'top';
bottom--;
} else if (direction == 'top') {
for (let i = bottom; i >= top; i--) {
ret.push(matrix[i][left]);
}
direction = 'right';
left++;
}
}
return ret;
};