Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save hassam-saeed/4927c8e1c0e88c6d2586ec736e5b7f43 to your computer and use it in GitHub Desktop.
Save hassam-saeed/4927c8e1c0e88c6d2586ec736e5b7f43 to your computer and use it in GitHub Desktop.
Spiral Matrix Code in JS
function spiralOrder(matrix) {
if (!matrix.length || !matrix[0].length) return [];
const result = [];
const rows = matrix.length, cols = matrix[0].length;
let top = 0, bottom = rows - 1, left = 0, right = cols - 1;
while (top <= bottom && left <= right) {
// Traverse right
for (let i = left; i <= right; i++) {
result.push(matrix[top][i]);
}
top++;
// Traverse down
for (let i = top; i <= bottom; i++) {
result.push(matrix[i][right]);
}
right--;
// Traverse left (only if there are more elements in the row)
if (top <= bottom) {
for (let i = right; i >= left; i--) {
result.push(matrix[bottom][i]);
}
bottom--;
}
// Traverse up (only if there are more elements in the column)
if (left <= right) {
for (let i = bottom; i >= top; i--) {
result.push(matrix[i][left]);
}
left++;
}
}
return result;
}
const matrix =
[[1,2,3],
[4,5,6],
[7,8,9] ];
const response = spiralOrder(matrix)
console.log(response);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment