Traversing the Matrix in Spiral Order

Let's begin solving with an example. Suppose we are given an m * n matrix. The simplest way to traverse the matrix in spiral order is as shown in the figure below:

Getting the Specs

You can see the development of the traversal in 3 stages. We start at the top left corner, and traverse the outer rows and columns of the matrix and repeat the same on the inner rows and columns.

  • First, there's the yellow outer ring portion.
  • Then, once we get to the 6 in matrix[0][1], we encounter the green portion.
  • Once we get to the 12 in matrix[1][2], we finally are in the middle (and final) cell.

So we're building a bit of intuition now. This is how we get good at solving these types of interview questions! We are taking a complex problem and breaking it down. In this case, we essentially need to "transition" from the outer rings to inner. To do this, we'll need some variables for tracking when to make the switch.

colLower and colUpper variables keep track of the outer left and right columns, respectively. Also, rowLower and rowUpper keep track of the outer upper and bottom rows respectively of the matrix.