54. Spiral MatrixMedium12.5K1.1KCompanies
Input: matrix = [[1,2,3],[4,5,6],[7,8,9]]
Output: [1,2,3,6,9,8,7,4,5]
Input: matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]
Output: [1,2,3,4,8,12,11,10,9,5,6,7]
/**
* @param {number[][]} matrix
* @return {number[]}
*/
var spiralOrder = function (m) {
let w = m[0].length;
let h = m.length - 1;
const answer = [];
let row = 0;
let col = -1;
while (w >= 0 && h >= 0) {
col++;
for (let i = 0; i < w; i++) {
const curr = m[row][col];
answer.push(curr);
col++;
}
w--;
if (w < 0) break;
col--;
row++;
for (let i = 0; i < h; i++) {
const curr = m[row][col];
answer.push(curr);
row++;
}
h--;
if (h < 0) break;
row--;
col--;
for (let i = 0; i < w; i++) {
const curr = m[row][col];
answer.push(curr);
col--;
}
w--;
if (w < 0) break;
col++;
row--;
for (let i = 0; i < h; i++) {
const curr = m[row][col];
answer.push(curr);
row--;
}
h--;
if (h < 0) break;
row++;
}
return answer;
};