Skip to content

Commit

Permalink
*
Browse files Browse the repository at this point in the history
  • Loading branch information
imteekay committed Jan 3, 2024
1 parent 51a1a8e commit 604997c
Showing 1 changed file with 57 additions and 0 deletions.
57 changes: 57 additions & 0 deletions coding_interviews/algoexpert/spiral-traverse/spiral-traverse.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
// Right: keep the row and increase the column
// Bottom: keep the column and increase the row
// Left: keep the row and decrease the column
// Top: keep the column and decrease the row

function spiralTraverse(array) {
let row = 0;
let col = 0;
let endRow = array.length - 1;
let endCol = array[0].length - 1;
let output = [];
let command = 'R';

while (col <= endCol && row <= endRow) {
if (command === 'R') {
for (let index = col; index <= endCol; index++) {
output.push(array[row][index]);
}

row++;
command = 'B';
continue;
}

if (command === 'B') {
for (let index = row; index <= endRow; index++) {
output.push(array[index][endCol]);
}

endCol--;
command = 'L';
continue;
}

if (command === 'L') {
for (let index = endCol; index >= col; index--) {
output.push(array[endRow][index]);
}

endRow--;
command = 'T';
continue;
}

if (command === 'T') {
for (let index = endRow; index >= row; index--) {
output.push(array[index][col]);
}

col++;
command = 'R';
continue;
}
}

return output;
}

0 comments on commit 604997c

Please sign in to comment.