Created
June 20, 2017 04:45
-
-
Save theptrk/42181f52bbf7325cda2901f6f11f36c7 to your computer and use it in GitHub Desktop.
Spiral Traversal of 2D array in JavaScript
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 test1 = [ | |
[1] | |
]; | |
const test2 = [ | |
[1, 2], | |
[3, 4] | |
]; | |
const test3 = [ | |
[1, 2, 3], | |
[4, 5, 6], | |
[7, 8, 9] | |
]; | |
const test4 = [ | |
[1,2,3,4], | |
[5,6,7,8], | |
[9,1,2,3], | |
[4,5,6,7] | |
]; | |
const test5 = [ | |
[1,2,3,4,5], | |
[6,7,8,9,0], | |
[1,2,3,4,5], | |
[6,7,8,9,0], | |
[1,2,3,4,5] | |
]; | |
// assume a square matrix | |
const spiralTraversal = (matrix, cb) => { | |
let cycles = matrix.length; | |
for (let cycle = 0; cycle < cycles; cycle++) { | |
traverseCycle(matrix, cycle, cb); | |
} | |
}; | |
const traverseCycle = (matrix, cycle, cb) => { | |
let indexedSize = matrix.length - 1; | |
// we are at the midpoint of a odd sized matrix | |
if (cycle + 0.5 === matrix.length/2) { | |
cb(matrix[cycle][cycle]); | |
return; | |
} | |
// going right | |
for (let row = cycle, col = 0 + cycle; col < indexedSize - cycle; col++) { | |
cb(matrix[row][col]); | |
} | |
// going down | |
for (let row = cycle, col = indexedSize - cycle; row < indexedSize - cycle; row++) { | |
cb(matrix[row][col]); | |
} | |
// going left | |
for (let row = indexedSize - cycle, col = indexedSize - cycle; col > cycle; col--) { | |
cb(matrix[row][col]); | |
} | |
// going up | |
for (let row = indexedSize - cycle, col = cycle; row > cycle; row--) { | |
cb(matrix[row][col]); | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment