原题
给你一个 m
行 n
列的矩阵 matrix
,请按照 ,返回矩阵中的所有元素。
输入:matrix = [1,2,3],[4,5,6],[7,8,9] 输出:[1,2,3,6,9,8,7,4]
输入:matrix = [1,2,3,4],[5,6,7,8] 输出:[1,2,3,4,8,12,11,10,9,5,6,7]
题解
- 模拟
/** * @param {number[][]} matrix * @return {number[]} */ var spiralOrder = function(matrix) {
let top = 0, left = 0, right = matrix[0].length-1, botton = matrix.length - 1; let res = []; while(top <= botton && left <= right) {
for(let i = left; i <= right; i ) {
res.push(matrix[top][i]); } for(let i = top 1; i <= botton; i ) {
res.push(matrix[i][right]); } if(top != botton && left != right){
for
(
let i
= right
-
1
; i
>= left
; i
--
)
{
res
.
push
(matrix
[botton
]
[i
]
)
;
}
for
(
let i
= botton
-
1
; i
> top
; i
--
)
{
res
.
push
(matrix
[i
]
[left
]
)
;
}
}
[top
, left
, right
, botton
]
=
[top
+
1
, left
+
1
, right
-
1
, botton
-
1
]
;
}
return res
;
}
;