/*
* @lc app=leetcode.cn id=54 lang=javascript
*
* [54] 螺旋矩阵
*/
// @lc code=start
/**
* @param {number[][]} matrix
* @return {number[]}
*/
var spiralOrder = function (matrix) {
const m = matrix.length
const n = matrix[0].length
let left = 0;
let right = n - 1;
let top = 0;
let bottom = m - 1;
const ans = []
while (left <= right && top <= bottom) {
// 左 -> 右
for (let i = left; i <= right; i++) {
ans.push(matrix[top][i]);
}
top++
// 上 -> 下
for (let i = top; i <= bottom; i++) {
ans.push(matrix[i][right])
}
right--
// 右 -> 左
if (top <= bottom) {
for (let i = right; i >= left; i--) {
ans.push(matrix[bottom][i])
}
}
bottom--
// 下 -> 上
if (left <= right) {
for (let i = bottom; i >= top; i--) {
ans.push(matrix[i][left])
}
}
left++
}
return ans;
};
// @lc code=end
console.log(spiralOrder([[1, 2, 3], [4, 5, 6], [7, 8, 9]]))
console.log(spiralOrder([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]))