https://leetcode.com/problems/spiral-matrix/

开始还想用递归来遍历输出,但是需要对数组进行裁剪,处理麻烦而且占用空间。
遇到这种map问题可以用变量来标志范围。

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
/**
* @param {number[][]} matrix
* @return {number[]}
*/
var spiralOrder = function(matrix) {
let ret = []
if (matrix.length ===0) return ret
let rowBegin = 0
let rowEnd = matrix.length - 1
let colBegin = 0
let colEnd = matrix[0].length - 1
while(rowBegin <= rowEnd && colBegin <= colEnd) {
for (let i = colBegin; i <= colEnd; i++) {
ret.push(matrix[rowBegin][i])
}
rowBegin++
for (let i = rowBegin; i <= rowEnd; i++) {
ret.push(matrix[i][colEnd])
}
colEnd--
if (rowBegin <= rowEnd) {
for (let i = colEnd; i >= colBegin; i--) {
ret.push(matrix[rowEnd][i])
}
}
rowEnd--
if (colBegin <= colEnd) {
for (let i = rowEnd; i >= rowBegin; i--) {
ret.push(matrix[i][colBegin])
}
}
colBegin++
}
return ret
};