Created
May 24, 2021 11:10
-
-
Save hk-skit/9cdf31b97316d957cfadee1dd2aaefb7 to your computer and use it in GitHub Desktop.
Print matrix in spiral order
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const Direction = { | |
L_R: 0, | |
T_B: 1, | |
R_L: 2, | |
B_T: 3, | |
}; | |
const spiral = (matrix) => { | |
if (matrix.length === 0) { | |
return; | |
} | |
let left = 0, | |
right = matrix[0].length, | |
top = 0, | |
bottom = matrix.length; | |
while (right > left && bottom > top) { | |
// left to right - top most row | |
for (let i = left; i < right; i += 1) { | |
console.log(matrix[left][i]); | |
} | |
// shrink by top row. | |
top += 1; | |
// top to bottom - right most column | |
for (let i = top; i < bottom; i += 1) { | |
console.log(matrix[i][right - 1]); | |
} | |
// shrink right row; | |
right -= 1; | |
if (top < bottom) { | |
// right to left - bottom most row | |
for (let i = right - 1; i >= left; i -= 1) { | |
console.log(matrix[bottom - 1][i]); | |
} | |
// shrink bottom row | |
bottom -= 1; | |
} | |
if (left < right) { | |
// bottom to top - left most column | |
for (let i = bottom - 1; i >= top; i -= 1) { | |
console.log(matrix[i][left]); | |
} | |
// shrink left row; | |
left += 1; | |
} | |
} | |
}; | |
const _spiral = (matrix) => { | |
if (matrix.length === 0) { | |
return; | |
} | |
let dir = Direction.L_R; | |
let left = 0, | |
right = matrix[0].length - 1, | |
top = 0, | |
bottom = matrix.length - 1; | |
while (right >= left && bottom >= top) { | |
// Left to right | |
if (dir === Direction.L_R) { | |
for (let i = left; i <= right; i += 1) { | |
console.log(matrix[left][i]); | |
} | |
// shrink by top row. | |
top += 1; | |
dir = Direction.T_B; | |
} | |
// top to bottom | |
else if (dir === Direction.T_B) { | |
for (let i = top; i <= bottom; i += 1) { | |
console.log(matrix[i][right]); | |
} | |
// shrink right row; | |
right -= 1; | |
dir = Direction.R_L; | |
} | |
// bottom to right | |
else if (dir === Direction.R_L) { | |
for (let i = right; i >= left; i -= 1) { | |
console.log(matrix[bottom][i]); | |
} | |
// shrink bottom row | |
bottom -= 1; | |
dir = Direction.B_T; | |
} else if (dir === Direction.B_T) { | |
for (let i = bottom; i >= top; i -= 1) { | |
console.log(matrix[i][left]); | |
} | |
// shrink left row; | |
left += 1; | |
dir = Direction.L_R; | |
} | |
} | |
}; | |
const matrix = [ | |
[1, 2, 3], | |
[4, 5, 6], | |
[7, 8, 9], | |
]; | |
spiral(matrix); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment