/**
* @param {number[][]} matrix
* @return {number[]}
*/
var spiralOrder = function (matrix) {
const m = matrix.length
const n = matrix[0].length
const ans = []
let left = 0, top = 0, right = n - 1, bottom = m - 1
while (left <= right && top <= bottom) {
for (let i = left; i <= right; i++) ans.push(matrix[top][i])
if (++top > bottom) break;
for (let i = top; i <= bottom; i++) ans.push(matrix[i][right])
if (--right < left) break;
for (let i = right; i >= left; i--) ans.push(matrix[bottom][i])
if (bottom-- < top) break;
for (let i = bottom; i >= top; i--) ans.push(matrix[i][left])
if (++left > right) break;
}
return ans
};