Algorithm series: Spiral Matrix

Let’s talk about what is a Spiral Matrix. The Spiral Matrix problem takes 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 center of this matrix, in a clockwise manner.

The problem:


  • matrix(2)



  • matrix(3)




  • matrix(4)





  1. create a counter variable starting at 1
  2. As long as (start column ≤ end column) AND (start row ≤ end row)
  • Loop from start column to end column
  • At results[start_row][i] assign counter variable
  • Increment counter
  • Loop from start row to end row
  • At results [i][rend_column] assign counter variable
  • Increment counter
  • Decrement end row
  • …repeat for other two sides

Junior Full-Stack Web Developer. Looking for opportunities!