Skip to content

Instantly share code, notes, and snippets.

@theptrk
Created June 20, 2017 04:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save theptrk/42181f52bbf7325cda2901f6f11f36c7 to your computer and use it in GitHub Desktop.
Save theptrk/42181f52bbf7325cda2901f6f11f36c7 to your computer and use it in GitHub Desktop.
Spiral Traversal of 2D array in JavaScript
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