54. Spiral Matrix
Last updated
Last updated
/**
* @param {number[][]} matrix
* @return {number[]}
*/
var spiralOrder = function(matrix) {
const answer = [];
const colLen = matrix[0].length;
const rowLen = matrix.length;
let col = -1;
let row = 0;
let colStep = colLen;
let rowStep = rowLen - 1;
while (true) {
for (let i = 0; i < colStep; i++) {
col++;
answer.push(matrix[row][col]);
}
colStep--;
if (rowStep === 0) break;
for (let i = 0; i < rowStep; i++) {
row++;
answer.push(matrix[row][col]);
}
rowStep--;
if (colStep === 0) break;
for (let i = 0; i < colStep; i++) {
col--;
answer.push(matrix[row][col]);
}
colStep--;
if (rowStep === 0) break;
for (let i = 0; i < rowStep; i++) {
row--;
answer.push(matrix[row][col]);
}
rowStep--;
if (colStep === 0) break;
}
return answer;
};