Interview Questions

Print a matrix in spiral order

The input for this problem will be a matrix, or multidimensional array, which will be represented by N arrays each of N length, and your goal is to print the matrix in a spiral order. For example, if the input is:
[[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
then this matrix should be printed out in a list like so:
[1, 2, 3, 6, 9, 8, 7, 4, 5]
The spiral begins at the top left of the matrix and loops around it towards the center in a clockwise pattern. Below is a clever algorithm that uses recursion to print a matrix in spiral order:
## Algorithm

You need to be a premium member to see the rest of this question and code.

With our large collection of challengs, tutorials, and solutions, we make it easy for you to become a better coder, prepare for interviews, and learn new skills from more experienced coders.

developer.” ― Josh Aharonoff

- 200+ Coding Challenges
- Mock Interview Questions
- 500,000+ Code Solutions
- Algorithm Tutorials
- Interview Prep Courses

mrdaniel
published this on 11/12/15 **|**

2

I tried this way.........

function spiral(matrix){ var list= []; while(matrix.length>1){ //Right list= list.concat(matrix.splice(0,1)[0]); //Down for(var idx in matrix){ list.push(matrix[idx].splice(-1)[0]); } //Left list= list.concat(matrix.splice(-1,1)[0].reverse()); //Up for(var idx=matrix.length-1;idx>=0;idx--){ list.push(matrix[idx].splice(0,1)[0]); } } if(matrix.length>0){ list.push(matrix.pop()[0]); } return list; } // setup a matrix var M = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]; // return it in spiral order spiral(M);

JibranGarcia

commented on 06/05/16

Login to submit a comment