Skip to content

Instantly share code, notes, and snippets.

@melwyn95
Created July 7, 2020 10:30
Show Gist options
  • Save melwyn95/c27c5e3ccdff5caa83846767b293b6ec to your computer and use it in GitHub Desktop.
Save melwyn95/c27c5e3ccdff5caa83846767b293b6ec to your computer and use it in GitHub Desktop.
Spiral traversal
const arr_odd = [
[1, 2, 3, 4, 5],
[16, 17, 18, 19, 6],
[15, 24, 25, 20, 7],
[14, 23, 22, 21, 8],
[13, 12, 11, 10, 9]
];
const arr_even = [
[1, 2, 3, 4, 5, 6],
[20, 21, 22, 23, 24, 7],
[19, 32, 33, 34, 25, 8],
[18, 31, 36, 35, 26, 9],
[17, 30, 29, 28, 27, 10],
[16, 15, 14, 13, 12, 11]
];
// U -> R
// R -> D
// D -> L
// L -> U
function walk(arr) {
const result = [];
const size = arr[0].length;
function up(row, col, limit) {
if (!limit) return;
let t = limit;
while (t--) result.push(arr[row--][col]);
right(row + 1, col + 1, limit);
}
function right(row, col, limit) {
if (!limit) return;
let t = limit;
while (t--) result.push(arr[row][col++]);
down(row + 1, col - 1, limit - 1);
}
function down(row, col, limit) {
if (!limit) return;
let t = limit;
while (t--) result.push(arr[row++][col]);
left(row - 1, col - 1, limit);
}
function left(row, col, limit) {
if (!limit) return;
let t = limit;
while (t--) result.push(arr[row][col--]);
up(row - 1, col + 1, limit - 1);
}
right(0, 0, size)
return result;
}
function check(result, size) {
const correct = [];
let t = size * size
while (t--) correct.unshift(t + 1);
while (size--)
if (result[size-1] !== correct[size-1])
throw new Error("wrong answer")
return "correct answer"
}
console.log(check(walk(arr_odd), arr_odd.length));
console.log(check(walk(arr_even), arr_even.length));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment