Problem overview
The method SpiralOrder receives a matrix as an int[][], with m rows and n columns, and returns a List<int> of all its elements in spiral order. The spiral starts at the top-left corner and goes clockwise around the outside: along the top row to the right, down the right column, back along the bottom row to the left, and up the left column. It then repeats on whatever is left inside, until every element has been visited exactly once. The method should run in O(m * n) time.
For {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}} the result is [1, 2, 3, 6, 9, 8, 7, 4, 5]: the outer ring, then the single element 5 left in the middle. For a matrix with 3 rows and 4 columns the second ring is a single row, 6, 7, which is read left to right.
Approach: four boundaries that move inward
There is no clever formula here: the idea is to keep track of which rectangle is still unvisited. Four integers describe it: top and bottom are the first and last unvisited rows, and left and right are the first and last unvisited columns. Each lap walks the four sides of that rectangle in clockwise order, and every time a side is finished, its boundary moves one step inward. The loop ends when a pair of boundaries crosses, because then nothing is left.
Visiting each element once makes this O(m * n). The alternative, marking visited cells in a second matrix and turning right whenever the next cell is taken, works too but needs extra memory. The boundaries need only four variables.
The only delicate part is a rectangle that has become a single row or a single column. Then the "bottom side" is the same row as the top side, and the "left side" is the same column as the right side. Walking them would visit those elements a second time. The two if checks guard exactly that.
Tracing the 3x4 matrix {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}} shows the boundaries at work. The first lap starts with top = 0, bottom = 2, left = 0, right = 3 and adds 1, 2, 3, 4, 8, 12, 11, 10, 9, 5. The second lap starts with top = 1, bottom = 1, left = 1, right = 2: a single row. It adds 6, 7, and then the boundaries end at top = 2, bottom = 1, left = 2, right = 1, so the loop condition fails. In that second lap, the top-side walk reads the row, top++ pushes top past bottom, and the bottom-side if is skipped.
Step by step
- Create the empty list
resultthat collects elements in visiting order. - Set the row boundaries:
top = 0andbottom = matrix.Length - 1. - Set the column boundaries:
left = 0andright = matrix[0].Length - 1. All rows have the same length, so the first row tells how many columns there are. - Loop while
top <= bottom && left <= right. As long as neither pair has crossed, there are unvisited cells. - Top side: walk
colfromlefttoright, addingmatrix[top][col]. Then dotop++. Movingtopimmediately keeps the top-right corner from being added again by the next side. - Right side: walk
rowfromtop(already moved) tobottom, addingmatrix[row][right]. Then doright--. - Bottom side, only if
top <= bottom: walkcolfromrightdown toleft, addingmatrix[bottom][col], then dobottom--. If only one row was left, the top-side walk already read it, andtophas gone pastbottom. - Left side, only if
left <= right: walkrowfrombottomup totop, addingmatrix[row][left], then doleft++. If only one column was left, the right-side walk already read it. - Return
resultafter the loop.
The solution in C#
class Solution {
public List<int> SpiralOrder(int[][] matrix) {
List<int> result = new List<int>();
int top = 0, bottom = matrix.Length - 1;
int left = 0, right = matrix[0].Length - 1;
while (top <= bottom && left <= right) {
for (int col = left; col <= right; col++) {
result.Add(matrix[top][col]);
}
top++;
for (int row = top; row <= bottom; row++) {
result.Add(matrix[row][right]);
}
right--;
if (top <= bottom) {
for (int col = right; col >= left; col--) {
result.Add(matrix[bottom][col]);
}
bottom--;
}
if (left <= right) {
for (int row = bottom; row >= top; row--) {
result.Add(matrix[row][left]);
}
left++;
}
}
return result;
}
}
C# details worth knowing:
List<int>lives inSystem.Collections.Generic, so a standalone file needsusing System.Collections.Generic;. A list grows as youAdd, unlike an array whose length is fixed when it is created.- Several variables in one declaration.
int top = 0, bottom = matrix.Length - 1;declares twointvariables, each with its own initial value. - Jagged array.
int[][]is an array of row arrays, so the row count ismatrix.Lengthand the column count ismatrix[0].Length, and cells are read asmatrix[row][col]. - The input is only read. Unlike in-place matrix problems, nothing in
matrixchanges.
Complexity
Time: O(m * n). Each element is added exactly once, and the checks around the loops add constant work per lap.
Space: O(1) extra, apart from the returned list, which holds all m * n elements.
Edge cases and common mistakes
- A single row.
{{1, 2, 3}}returns[1, 2, 3]. After the top side,topbecomes 1 andbottomis 0, so the bottom side is skipped. - A single column.
{{3}, {2}, {1}}returns[3, 2, 1]. After the right side,rightdrops belowleft, so the left side is skipped. - A single element.
{{4}}returns[4]. - A 2x2 matrix.
{{1, 2}, {3, 4}}returns[1, 2, 4, 3]. - Not rectangular. A square-only solution that uses
nfor both dimensions would break on a 3x4 matrix. Keep separate row and column boundaries. - Skipping the two
ifchecks. On one remaining row or column, the last two sides repeat elements and the list ends up with duplicates. - Moving a boundary late. If
top++comes after the right-side loop, the top-right corner is added twice.
Testing
{{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}gives[1, 2, 3, 6, 9, 8, 7, 4, 5].{{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}}gives[1, 2, 3, 4, 8, 12, 11, 10, 9, 5, 6, 7].{{3}, {2}, {1}}gives[3, 2, 1].{{1, 2, 3}}gives[1, 2, 3].{{1, 2}, {3, 4}}gives[1, 2, 4, 3].
