Created
January 20, 2021 20:34
-
-
Save venil7/a00af418dcdbfc44c171721676438efb to your computer and use it in GitHub Desktop.
traverse matrix in spiral
This file contains 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 a = [ | |
[1, 2, 3, 4, 5, 6], | |
[1, 2, 3, 4, 5, 6], | |
[1, 2, 3, 4, 5, 6], | |
[1, 2, 3, 4, 5, 6], | |
[1, 2, 3, 4, 5, 6], | |
[1, 2, 3, 4, 5, 6], | |
]; | |
enum Dir { | |
east, south, west, north | |
} | |
const spiral = (matrix: number[][]): number[] => { | |
let res = []; | |
let [height, width] = [a.length, a[0].length]; | |
let [nw, ew, sw, ww] = [0, width-1, height-1, 0]; | |
let dir: Dir = Dir.east; | |
let [x, y] = [-1, 0]; | |
while (res.length < width * height) { | |
switch (dir) { | |
case Dir.east: | |
if (x < ew) { | |
x += 1; | |
} else { | |
nw += 1; | |
dir = Dir.south; | |
continue; | |
} | |
break; | |
case Dir.south: | |
if (y < sw) { | |
y += 1; | |
} else { | |
ew -= 1; | |
dir = Dir.west; | |
continue; | |
} | |
break; | |
case Dir.west: | |
if (x > ww) { | |
x -= 1; | |
} else { | |
sw -= 1; | |
dir = Dir.north; | |
continue; | |
} | |
break; | |
case Dir.north: | |
if (y > nw) { | |
y -= 1; | |
} else { | |
ww += 1; | |
dir = Dir.east; | |
continue; | |
} | |
break; | |
} | |
res.push(matrix[y][x]); | |
} | |
return res; | |
}; | |
console.log(spiral(a)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment