Solving the spiral matrix algorithm in JavaScript
26 January, 2022
3
3
1
Contributors
What is a spiral matrix?
The Spiral Matrix problem takes a 2-Dimensional array of N-rows and M-columns as an input, and prints the elements of this matrix in spiral order. The spiral begins at the top left corner of the input matrix, and prints the elements it encounters, while looping towards the centre of this matrix, in a clockwise manner.
This was one of the hardest algorithms so far, it took some time for it to click to how I should approach solving this algorithm. Once I figured out I needed to go from one corner point to the next without revisiting the previous node, I started to figure a way to go from top left corner → top right corner → bottom right corner → bottom left corner. From here I just needed to repeat the process
Instructions
Write a function that accepts an integer N and returns NxN spiral matrix.
Note: You are able to assign values to indices that have not yet been assigned in an array.
Create empty array of arrays called 'results'
Create a counter variable, starting at 1
Create variables to track, start row, end row, start column and end column
As long as (start column ≤ end column) AND (start row ≤ end row
Top Row
Loop from start column to end column
At results[startRow][i] assign counter variable
Increment counter
Increment start now
Right column
Loop from start row to end row
At results[i][endColumn] assign counter variable
Increment Counter
Decrement end row
...repeat for other two sides
Finally return the results
Full Code
javascript
learning
algorithms