Spiral Matrix II

Fill an n × n grid with the numbers 1 to n² in clockwise spiral order, starting at the top-left corner.

Given a number n, build a square grid with n rows and n columns, and fill it with the numbers 1 to n2. The numbers start in the top-left corner and run clockwise in a spiral: along the top row, down the right side, back along the bottom, up the left side, and then round again further in.

Example 1
Input: n = 3
Output: [[1, 2, 3], [8, 9, 4], [7, 6, 5]]
Example 2
Input: n = 1
Output: [[1]]
Solution

The Idea

Picture someone mowing a square lawn. They start at one corner, follow the edge all the way round, and then keep circling inward, each lap a little smaller, until they finish in the middle. The numbers in this problem travel the same path, and each cell they pass gets the next number.

For n = 3 the grid has three rows and three columns, numbered from 0. Write a cell's place as "row r, col c", so the top-left corner is row 0, col 0. The numbers 1, 2 and 3 go along row 0. Then 4 and 5 go down col 2, and 6 and 7 go back along row 2. Next, 8 goes up col 0, and 9 lands in the middle, row 1, col 1.

Following the path by hand is easy, because you can see the edge of the grid and the cells you have already filled. A program cannot see them. How does it know where a side ends and where to turn?

Left: a 3 by 3 grid with arrows through 1 to 9. The first ring is the top row 1, 2, 3, the right column 4, 5, the bottom row 6, 7 from right to left, and the left column 8. The middle cell, 9, is the inner ring. Right: after the first ring the borders are top = 1, bottom = 1, left = 1, right = 1, and only row 1, col 1 is left.

In the left half of the picture, the blue cells form the outer ring of the grid. Each label around it names one side, and each side is a whole row or column of the cells still empty when that side starts. The "top row" label covers 1, 2, 3 in row 0. Once row 0 is full, the empty part starts one row lower.

So the empty part is always a rectangle, and four numbers describe it: its first row, its last row, its first column and its last column. Call them top, bottom, left and right. Filling a side means walking along one of these edges, then moving that edge inward by one.

The right half of the picture shows the borders after the first ring: "top = 1, bottom = 1" and "left = 1, right = 1". The empty part has shrunk to the single orange cell at row 1, col 1, and the next ring fills it with 9. Each ring is a smaller copy of the same job.

Solution Approach

The border idea leaves three questions for the code: how to track the empty part, in which order to fill the sides so no corner is written twice, and when to stop. There is also a way to steer without borders, by walking and turning.

Four borders for the empty part

Where is the empty part at the start? It is the whole grid, so top and left start at 0, and bottom and right start at n - 1. A counter named value holds the next number to write, starting at 1, and goes up by one after every write.

Filling the sides and their corners

Which side writes a corner, such as row 0, col 2 in Example 1? The top row writes it, because it runs from left all the way to right. Right after that, top moves down by one, so the right column starts one row lower and never touches that corner again.

The same pattern repeats on every side. Fill it, then move its border inward before the next side starts. The right column moves right left, the bottom row moves bottom up, and the left column moves left right. In the picture, that is why 3, 5 and 7 each belong to one side only.

When to stop

How does the program know the grid is full? The rings stop once top has moved below bottom, because then no row of the empty part is left. In a square, each ring moves all four borders inward by one, so left passes right in the same ring and one check is enough.

When n is odd, the last ring is one cell, like the 9 in Example 1. The top row writes it and moves top below bottom. The other three sides then have nothing to walk over, so their loops do not run. Code that fills a rectangle of any shape adds extra checks inside the bottom and left sides. For a square they change nothing: a test run over every n from 0 to 50 gave the same grids with and without them.

Another way: walking and turning

Is there a way without borders? You can walk like the mower does: keep a direction (right, down, left, up), and turn clockwise whenever the next cell is outside the grid or already holds a number. That replaces the four borders with a test at every step. A run over every n from 0 to 50 gave the same grids as the border version, so either works; the border version keeps each side as one plain loop.

Java Solution

The method generateMatrix works in these steps:

  1. First, create the grid m with new int[n][n]. Java fills it with zeros.
  2. Set the four borders top = 0, bottom = n - 1, left = 0 and right = n - 1, and the counter value = 1.
  3. A while loop fills one ring per round, as long as top <= bottom. Inside it, a first for loop moves c from left to right and writes the top row; then top goes down by one.
  4. A second loop moves r from top down to bottom and writes the right column; then right goes left by one.
  5. A third loop moves c from right back to left along the bottom row; then bottom goes up by one. A fourth loop moves r from bottom up to top along the left column; then left goes right by one.
  6. Every write puts value in the cell and then adds one to it. When the while loop ends, return m.

The main method prints the grid row by row for both examples, then for n = 2, n = 4 and n = 0.

Java
import java.util.Arrays;

public class SpiralMatrixII {

    public static int[][] generateMatrix(int n) {
        int[][] m = new int[n][n];
        int top = 0, bottom = n - 1, left = 0, right = n - 1;
        int value = 1;
        while (top <= bottom) {
            for (int c = left; c <= right; c++) {
                m[top][c] = value++;                  // top row, left to right
            }
            top++;
            for (int r = top; r <= bottom; r++) {
                m[r][right] = value++;                // right column, downwards
            }
            right--;
            for (int c = right; c >= left; c--) {
                m[bottom][c] = value++;               // bottom row, right to left
            }
            bottom--;
            for (int r = bottom; r >= top; r--) {
                m[r][left] = value++;                 // left column, upwards
            }
            left++;
        }
        return m;
    }

    static void show(int n) {
        System.out.println("n = " + n + ":");
        int[][] m = generateMatrix(n);
        if (m.length == 0) {
            System.out.println("[]");
        }
        for (int[] row : m) {
            System.out.println(Arrays.toString(row));
        }
    }

    public static void main(String[] args) {
        show(3);
        show(1);
        show(2);
        show(4);
        show(0);
    }
}

Running it prints:

Output
n = 3:
[1, 2, 3]
[8, 9, 4]
[7, 6, 5]
n = 1:
[1]
n = 2:
[1, 2]
[4, 3]
n = 4:
[1, 2, 3, 4]
[12, 13, 14, 5]
[11, 16, 15, 6]
[10, 9, 8, 7]
n = 0:
[]

The grid for n = 3 reads [1, 2, 3], [8, 9, 4], [7, 6, 5], the same as Example 1, with 9 alone in the middle row. For n = 2 there is one ring and no middle cell: [1, 2] on top and [4, 3] below, since 3 and 4 run right to left.

Look at the grid for n = 4. The outer ring holds 1 to 12, and the numbers 13, 14, 15 and 16 fill rows 1 and 2, cols 1 and 2, as a second ring of two by two. The last block, for n = 0, prints []. There bottom starts at -1, so the while loop never runs and the empty grid comes back.

The order of top++ matters. If it moves to after the right-column loop, that loop starts on row 0, col 2 and writes over the 3. A run of that version for n = 3 printed [[1, 2, 4], [9, 11, 5], [8, 7, 6]]: the counter reached 11, and the numbers 3 and 10 are missing from the grid.

Complexity

Every cell is written once, and each ring adds a few border moves.

  • Time: O(n2), because the four side loops together write each of the n2 cells exactly once, and each of the about n/2 rings adds only four border moves.
  • Space: O(1) besides the grid that is returned, because apart from m the method keeps only the four borders, the counter and a loop index.

Reading an existing matrix in the same spiral order, where the grid can be a rectangle, is Spiral Matrix.