-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path54_javascript.js
More file actions
53 lines (49 loc) · 1.18 KB
/
54_javascript.js
File metadata and controls
53 lines (49 loc) · 1.18 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
// 给定一个包含 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]
/**
* @param {number[][]} matrix
* @return {number[]}
*/
var spiralOrder = function (matrix) {
let up = 0,
left = 0,
right = matrix[0].length - 1,
bottom = matrix.length - 1;
let res = [];
// 依次循环
while (true) {
for (let i = left; i <= right; i++) {
res.push(matrix[up][i]);
}
if (++up > bottom) break; // 设定边界
for (let j = up; j <= bottom; j++) {
res.push(matrix[j][right]);
}
if (--right < left) break;
for (let k = right; k >= left; k--) {
res.push(matrix[bottom][k]);
}
if (--bottom < up) break;
for (let h = bottom; h >= up; h--) {
res.push(matrix[h][left]);
}
if (++left > right) break;
}
return res;
};
// https://leetcode-cn.com/problems/spiral-matrix/solution/cxiang-xi-ti-jie-by-youlookdeliciousc-3/