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
Output: [1, 2, 3, 6, 9, 8, 7, 4, 5]
Example 2
Output: [1, 2, 3, 4, 8, 12, 11, 10, 9, 5, 6, 7]
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 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: topbottomleftright
Reading one lap
Which border moves after each side? The one that side used up. After reading the top row, toprightbottomleft
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 <= bottomleft <= right
A single row or column left over
What happens in the orange part? The second lap reads 6, 7 along the top row, and topbottomright
So before the bottom row the code checks top <= bottomleft <= right[[1], [2], [3]]
Java Solution
The method spiralOrder
- First, create the result list
. If the matrix has no rows, return it empty right away.order - Set the four borders of the unread rectangle:
to 0,top to the last row,bottom to 0 andleft to the last column.right - Start a
loop that runs one lap per pass, as long aswhile andtop <= bottom .left <= right - Inside the lap, a first
loop moves the column indexfor fromc toleft and adds the top row, thenright grows by one. A second loop moves the row indextop fromr totop down the right column, thenbottom shrinks by one.right - If
, a third loop reads the bottom row fromtop <= bottom back toright , thenleft shrinks by one. Ifbottom , a fourth loop reads the left column fromleft <= right up tobottom , thentop grows by one.left - After the last lap, return
.order
The main
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:
[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
The 3 by 2 matrix gives [1, 2, 4, 6, 5, 3][1, 2, 3]left <= right[]
Both guards matter. A version without them returns [1, 2, 3, 4, 8, 12, 11, 10, 9, 5, 6, 7, 6][1, 2, 3, 2]while<<=
Complexity
Every value is added to order
- 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