给你一个 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]
/**
* @param {number[][]} matrix
* @return {number[]}
*/
var spiralOrder = function (matrix) {
let row = matrix.length
let col = matrix[0].length
let top = 0, left = 0, right = col - 1, bottom = row - 1
let res = []
while (left < right && top < bottom) {
for (let i = top; i <= right; i++) {
res.push(matrix[top][i])
}
for (let i = top + 1; i <= bottom; i++) {
res.push(matrix[i][right])
}
for (let i = right - 1; i >= left; i--) {
res.push(matrix[bottom][i])
}
for (let i = bottom - 1; i >= top + 1; i--) {
res.push(matrix[i][left])
}
left++
top++
right--
bottom--
}
if (left == right&&top<=bottom) {
for (let i = top; i <= bottom; i++) {
res.push(matrix[i][left])
}
} else if (top == bottom&&left<right) {
for (let i = left; i <= right; i++) {
res.push(matrix[top][i])
}
}
return res
};
遍历顺序
特殊情况