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 nnn
Example 1
Output: [[1, 2, 3], [8, 9, 4], [7, 6, 5]]
Example 2
Output: [[1]]
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
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?
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 topbottomleftright
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 topleftbottomrightn - 1value
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 leftrighttop
The same pattern repeats on every side. Fill it, then move its border inward before the next side starts. The right column moves rightbottomleft
When to stop
How does the program know the grid is full? The rings stop once topbottomleftright
When ntopbottom
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
- First, create the grid
withm . Java fills it with zeros.new int[n][n] - Set the four borders
,top = 0 ,bottom = n - 1 andleft = 0 , and the counterright = n - 1 .value = 1 - A
loop fills one ring per round, as long aswhile . Inside it, a firsttop <= bottom loop movesfor fromc toleft and writes the top row; thenright goes down by one.top - A second loop moves
fromr down totop and writes the right column; thenbottom goes left by one.right - A third loop moves
fromc back toright along the bottom row; thenleft goes up by one. A fourth loop movesbottom fromr up tobottom along the left column; thentop goes right by one.left - Every write puts
in the cell and then adds one to it. When thevalue loop ends, returnwhile .m
The mainn = 2n = 4n = 0
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:
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[1, 2, 3][8, 9, 4][7, 6, 5]n = 2[1, 2][4, 3]
Look at the grid for n = 4n = 0[]bottomwhile
The order of top++n = 3[[1, 2, 4], [9, 11, 5], [8, 7, 6]]
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
the method keeps only the four borders, the counter and a loop index.m
Reading an existing matrix in the same spiral order, where the grid can be a rectangle, is