54. Spiral Matrix
202410061620
tags: #array
var spiralOrder = function(matrix) {
const rows = matrix.length;
const cols = matrix[0].length;
let startRow = 0;
let endRow = rows - 1;
let startCol = 0;
let endCol = cols - 1;
const res = [];
while (res.length !== rows * cols) {
for (let i = startCol; i <= endCol; i++) {
res.push(matrix[startRow][i]);
}
startRow += 1;
for (let i = startRow; i <= endRow; i++) {
res.push(matrix[i][endCol]);
}
endCol -= 1;
if (startRow <= endRow) {
for (let i = endCol; i >= startCol; i--) {
res.push(matrix[endRow][i]);
}
}
endRow -= 1;
if (startCol <= endCol) {
for (let i = endRow; i >= startRow; i--) {
res.push(matrix[i][startCol]);
}
}
startCol += 1;
}
return res;
};