Skip to content

Instantly share code, notes, and snippets.

@owade
Created August 27, 2022 09:40
Show Gist options
  • Save owade/bcadc5119c6b7e690bd5ef2d08b9a32f to your computer and use it in GitHub Desktop.
Save owade/bcadc5119c6b7e690bd5ef2d08b9a32f to your computer and use it in GitHub Desktop.
Spiral matrix traversal
let i=0,j=0,res=[];
const traverse = (arr) => {
while(!visited(arr)){
goRight(arr);
goDown(arr);
goLeft(arr);
goUp(arr);
}
return res;
}
const goRight = (arr) => {
while(j< arr.length && arr[i][j] !== "#"){
res.push(arr[i][j]);
arr[i][j] = "#";
j++;
}
j-=1;
}
const goDown = (arr) => {
i+=1
while(i < arr.length && arr[i][j] !== "#"){
res.push(arr[i][j]);
arr[i][j] = "#";
i++;
}
i-=1;
}
const goLeft = (arr) => {
j-=1;
while(j>= 0 && arr[i][j] !== "#"){
res.push(arr[i][j]);
arr[i][j] = "#";
j--;
}
j+=1
}
const goUp = (arr) => {
i-=1;
while(i>= 0 && arr[i][j] !== "#"){
res.push(arr[i][j]);
arr[i][j] = "#";
i--;
}
i+=1;j+=1;
}
const visited = (arr) => {
let res = true
for(let i=0;i<arr.length;i++){
let r = arr[i].every(x => x === "#");
if(!r) return false;
}
return res;
}
let arr1 = [[1,2,3,4,5],
[6,7,8,9,10],
[11,12,13,14,15],
[16,17,18,19,20],
[21,22,23,24,25]]
let arr2 = [[1,2,3,4],
[6,7,8,9],
[11,12,13,14],
[16,17,18,19]]
let arr3 = [[1,2,3],
[6,7,8],
[11,12,13]]
console.log(traverse(arr1));
// [
// [ 0, 0 ], [ 0, 1 ], [ 0, 2 ], [ 0, 3 ], [ 0, 4 ],
// [ 1, 0 ], [ 1, 1 ], [ 1, 2 ], [ 1, 3 ], [ 1, 4 ],
// [ 2, 0 ], [ 2, 1 ], [ 2, 2 ], [ 2, 3 ], [ 2, 4 ],
// [ 3, 0 ], [ 3, 1 ], [ 3, 2 ], [ 3, 3 ], [ 3, 4 ],
// [ 4, 0 ], [ 4, 1 ], [ 4, 2 ], [ 4, 3 ], [ 4, 4 ]
// ]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment