给你一个 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
思路:
```javascript var spiralOrder = function (matrix) { if (matrix.length === 0) return [] const res = [] let top = 0, bottom = matrix.length - 1, left = 0, right = matrix[0].length - 1 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 (top === bottom) // 剩下一行,从左到右依次添加 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 };
<a name="OxtIy"></a>## 更简洁的方法1. 一次push一行/列1. **push完马上收缩边界,并判断是否超出边界**1. 一旦超出边界就break3. 这样就不用最后再来考虑有没有剩下的```javascriptconst spiralOrder = function (matrix) {if (matrix.length === 0) return [];let top = 0, bottom = matrix.length - 1,left = 0, right = matrix[0].length - 1;let res = [];while (true) {for (let i = left; i <= right; i++) res.push(matrix[top][i]);if (++top > bottom) break;for (let i = top; i <= bottom; i++) res.push(matrix[i][right]);if (--right < left) break;for (let i = right; i >= left; i--) res.push(matrix[bottom][i]);if (--bottom < top) break;for (let i = bottom; i >= top; i--) res.push(matrix[i][left]);if (++left > right) break;}return res;}
const spiralOrder = function (matrix) {
if (matrix.length === 0) return [];
let top = 0, bottom = matrix.length - 1,
left = 0, right = matrix[0].length - 1;
let res = [];
while (true) {
for (let i = left; i <= right; i++) res.push(matrix[top][i]);
if (++top > bottom) break;
for (let i = top; i <= bottom; i++) res.push(matrix[i][right]);
if (--right < left) break;
for (let i = right; i >= left; i--) res.push(matrix[bottom][i]);
if (--bottom < top) break;
for (let i = bottom; i >= top; i--) res.push(matrix[i][left]);
if (++left > right) break;
}
return res;
}
