Skip to content

Commit

Permalink
Complete spiralTraversal.js using recursion
Browse files Browse the repository at this point in the history
  • Loading branch information
fay-jai committed Jan 2, 2015
1 parent 42edbe5 commit f57b732
Showing 1 changed file with 57 additions and 3 deletions.
60 changes: 57 additions & 3 deletions spiralTraversal/spiralTraversal.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,61 @@
returns [1, 2, 3, 6, 9, 8, 7, 4, 5]
*/

var spiralTraversal = function(matrix){
// Solved recursively for any 2-dimensional array (even if inner arrays are not the same length)
var spiralTraversal = function (matrix) {
if (matrix.length === 0) return;

// TODO: Implement me!
};
var result = [];
var currentRow, currentCol;

var goRight = function (matrix) {
var currentRow = 0; // always remove first row
while ( matrix[currentRow].length > 0 ) {
result.push ( matrix[currentRow].shift() );
}
matrix.shift();
};

var goDown = function (matrix) {
var currentRow = 0; // always start at first row and remove last column in that row
while ( matrix[currentRow] !== void 0 && matrix[currentRow][ matrix[currentRow].length - 1] !== void 0 ) {
result.push( matrix[currentRow].pop() );
currentRow += 1;
}
};

var goLeft = function (matrix) {
var currentRow = matrix.length - 1; // always remove last row
while ( matrix[currentRow].length > 0 ) {
result.push( matrix[currentRow].pop() );
}
matrix.pop();
};

var goUp = function (matrix) {
var currentRow = matrix.length - 1; // always start at last row and remove first column in that row
while ( matrix[currentRow] !== void 0 && matrix[currentRow][0] !== void 0 ) {
result.push( matrix[currentRow].shift() );
currentRow -= 1;
}
};

var move = function () {
goRight(matrix);
if (matrix.length === 0) return;

goDown(matrix);
if (matrix.length === 0) return;

goLeft(matrix);
if (matrix.length === 0) return;

goUp(matrix);
if (matrix.length === 0) return;

if ( matrix.length > 0 ) move();
};

move();
return result;
};

0 comments on commit f57b732

Please sign in to comment.