Javascript Code
/**
* @param {number[][]} matrix
* @return {number[]}
*/
var spiralOrder = function (matrix) {
let top = 0, right = matrix[0].length, bottom = matrix.length, left = 0;
let res = [];
while (top < bottom && left < right) {
// complete the top row ( right to left)
for (let i = left; i < right; i++) {
res.push(matrix[top][i]);
}
top++;
// complete the right column ( top to bottom )
for (let i = top; i < bottom; i++) {
res.push(matrix[i][right - 1])
}
right--;
// Check if there are still rows and columns left
if (!(left < right && top < bottom)) break;
// complete the bottom row (left to right)
for (let i = right-1; i >= left; i--) {
res.push(matrix[bottom-1][i])
}
bottom--;
// complete the left column (bottom to top)
for (let i = bottom - 1; i >= top; i--) {
res.push(matrix[i][left]);
}
left++;
}
return res;
};
Top comments (0)