Spiral Matrix

Read every value of a matrix in a clockwise spiral, ring by ring, from the top-left corner inward.

Given a matrix with m rows and n columns, return all of its values in spiral order. Start at the top-left corner and go right along the top row, down the right column, left along the bottom row and up the left column. Then do the same on the part inside, until every value has been read once.

Example 1
Input: matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
Output: [1, 2, 3, 6, 9, 8, 7, 4, 5]
Example 2
Input: matrix = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]
Output: [1, 2, 3, 4, 8, 12, 11, 10, 9, 5, 6, 7]
Solution

The Idea

Imagine walking around a rectangular flower bed, clockwise, along its outer edge. When you are back near the start, you step one row inward and walk around the smaller rectangle inside. A spiral read of a matrix works the same way: one lap around the outside, then a lap around the inside, and so on.

Example 2 is a matrix of 3 rows and 4 columns, drawn in the picture below with its rows numbered 0 to 2 and its columns 0 to 3. Follow the arrows from the value 1 at row 0, col 0.

The 3 by 4 matrix of Example 2 with rows 0 to 2 and columns 0 to 3. The outer ring is read as the top row 1, 2, 3, 4, the right column 8, 12, the bottom row 11, 10, 9 and the left column 5. The inner part is a single row, 6, 7.

The first lap, in blue, has four sides. The top row gives 1, 2, 3, 4. The right column, col 3, gives 8 and 12, since 4 was already read. The bottom row, row 2, goes right to left and gives 11, 10, 9. The left column, col 0, goes upward and gives only 5, because 9 and 1 are taken.

Notice that the right, bottom and left sides each start one cell past a corner, because the side before them already read that corner. So how do we keep track of which cells are still unread, lap after lap?

Look at what is left after the first lap: the orange cells 6 and 7 at row 1, col 1 and row 1, col 2. The unread cells always form a smaller rectangle. A rectangle is described by four numbers: its first row, last row, first column and last column. After the first lap these are row 1, row 1, col 1 and col 2.

That orange part also shows the one tricky case. Its top row and its bottom row are the same row, so the second lap must read 6, 7 once and stop, not read the row a second time on its way back. Item 5 in the picture, "inner part, one row", is exactly that case.

Solution Approach

Three decisions turn the picture into code: how to remember the unread rectangle instead of marking cells, in what order to read and shrink its sides, and how to handle a leftover single row or column.

Keeping track of the unread rectangle

What is the simplest way to know where to turn? One way is to walk cell by cell with a second grid of true or false marks, turning right whenever the next cell is outside the matrix or already marked. That works, but it needs m × n extra marks.

The orange rectangle in the picture points to a cheaper record. Four whole numbers describe the unread rectangle: top is its first row, bottom its last row, left its first column and right its last column. All four are inclusive, so for Example 2 they start at 0, 2, 0 and 3.

Reading one lap

Which border moves after each side? The one that side used up. After reading the top row, top moves one row down, so the right column then starts below the corner already read. After the right column, right moves one column left, then bottom moves up after the bottom row, and left moves right after the left column.

In Example 2 the four borders go from 0, 2, 0, 3 to 1, 1, 1, 2 after the first lap. That is the orange rectangle: row 1 to row 1, col 1 to col 2. Laps go on while top <= bottom and left <= right, meaning at least one unread cell remains.

A single row or column left over

What happens in the orange part? The second lap reads 6, 7 along the top row, and top becomes 2, which is now below bottom, still 1. The right column has no cells left, and right becomes 1. If the bottom row were read now, it would be row 1 again, and 6 would come out twice.

So before the bottom row the code checks top <= bottom, and before the left column it checks left <= right. The second check covers a matrix of one column, such as [[1], [2], [3]], where the left column would otherwise read 2 a second time on its way up.

Java Solution

The method spiralOrder works in these steps:

  1. First, create the result list order. If the matrix has no rows, return it empty right away.
  2. Set the four borders of the unread rectangle: top to 0, bottom to the last row, left to 0 and right to the last column.
  3. Start a while loop that runs one lap per pass, as long as top <= bottom and left <= right.
  4. Inside the lap, a first for loop moves the column index c from left to right and adds the top row, then top grows by one. A second loop moves the row index r from top to bottom down the right column, then right shrinks by one.
  5. If top <= bottom, a third loop reads the bottom row from right back to left, then bottom shrinks by one. If left <= right, a fourth loop reads the left column from bottom up to top, then left grows by one.
  6. After the last lap, return order.

The main method runs both examples, a matrix of 3 rows and 2 columns, a single row, a single column, a single value and a matrix with no rows.

Java
import java.util.ArrayList;
import java.util.List;

public class SpiralMatrix {

    public static List<Integer> spiralOrder(int[][] matrix) {
        List<Integer> order = new ArrayList<>();
        if (matrix.length == 0) {
            return order;                          // no rows, nothing to read
        }
        int top = 0;
        int bottom = matrix.length - 1;
        int left = 0;
        int right = matrix[0].length - 1;
        while (top <= bottom && left <= right) {
            for (int c = left; c <= right; c++) {
                order.add(matrix[top][c]);         // top row, left to right
            }
            top++;
            for (int r = top; r <= bottom; r++) {
                order.add(matrix[r][right]);       // right column, downwards
            }
            right--;
            if (top <= bottom) {                   // a bottom row is still unread
                for (int c = right; c >= left; c--) {
                    order.add(matrix[bottom][c]);  // bottom row, right to left
                }
                bottom--;
            }
            if (left <= right) {                   // a left column is still unread
                for (int r = bottom; r >= top; r--) {
                    order.add(matrix[r][left]);    // left column, upwards
                }
                left++;
            }
        }
        return order;
    }

    public static void main(String[] args) {
        System.out.println(spiralOrder(new int[][] {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}));
        System.out.println(spiralOrder(new int[][] {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}}));
        System.out.println(spiralOrder(new int[][] {{1, 2}, {3, 4}, {5, 6}}));
        System.out.println(spiralOrder(new int[][] {{1, 2, 3, 4}}));
        System.out.println(spiralOrder(new int[][] {{1}, {2}, {3}}));
        System.out.println(spiralOrder(new int[][] {{7}}));
        System.out.println(spiralOrder(new int[][] {}));
    }
}

Running it prints:

Output
[1, 2, 3, 6, 9, 8, 7, 4, 5]
[1, 2, 3, 4, 8, 12, 11, 10, 9, 5, 6, 7]
[1, 2, 4, 6, 5, 3]
[1, 2, 3, 4]
[1, 2, 3]
[7]
[]

Example 1 ends with 5, the centre cell at row 1, col 1, which the second lap reads as a top row of one value. Example 2 ends with 6, 7, each once, which is the orange row from the picture. The guard top <= bottom stopped the bottom row from reading 6 again.

The 3 by 2 matrix gives [1, 2, 4, 6, 5, 3]: one lap reads every value, and its left column is just 3. The fifth line, [1, 2, 3], is the single column, where the guard left <= right kept 2 from appearing twice. The empty matrix returns [] before any border is set.

Both guards matter. A version without them returns [1, 2, 3, 4, 8, 12, 11, 10, 9, 5, 6, 7, 6] for Example 2 and [1, 2, 3, 2] for the single column. Writing the while condition with < instead of <= breaks it the other way: Example 1 loses the centre 5, and Example 2 loses 6 and 7.

Complexity

Every value is added to order once, and the method keeps only the four borders besides the result.

  • Time: O(m × n), because each lap's four loops touch only the cells of that lap's ring, and the borders move inward after every side, so each of the m × n values is read once.
  • Space: O(1) besides the output, because the unread rectangle is held in four whole numbers instead of a grid of marks, and the returned list holds the m × n values.

Filling a matrix with the numbers 1, 2, 3 and so on in the same spiral order is Spiral Matrix II.