LeetCode数组题(中级)--螺旋矩阵

给出一个 m x n 的矩阵(m 行, n 列),请按照顺时针螺旋顺序返回元素。

例如,给出以下矩阵:

1
2
3
4
5
[
[ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ]
]

应该返回 [1,2,3,6,9,8,7,4,5]

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
/**
* @param {number[][]} matrix
* @return {number[]}
*/
var spiralOrder = function(matrix) {
var reArr = []
this.reduceMat = function (mat) {
if (!this.isArray(mat)) return
let shiftArr = mat.shift()
reArr = reArr.concat(shiftArr)
if (!this.isArray(mat)) return
mat.map((arr) => {
reArr.push(arr.pop())
})
if (!this.isArray(mat)) return
reArr = reArr.concat(mat.pop().reverse())
if (!this.isArray(mat)) return
mat.reverse().map((arr) => {
let shiftArr = arr.shift()
reArr.push(shiftArr)
})
if (this.isArray(mat)) {
reduceMat(mat.reverse())
}
}
this.isArray = function (mat) {
return Object.prototype.toString.call(mat[0]) === '[object Array]' && mat[0].length > 0
}
this.reduceMat(matrix)
return reArr
};
投食二维码