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:

Example:

  • matrix(2)

[[1,2],

[3,4]]

  • matrix(3)

[[1,2,3],

[8,9,4],

[7,6,5]]

  • matrix(4)

[[1,2,3,4],

[12,13,14,5],

[11,16,15,6]]

Solution:

  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!