Problem overview
The method spiralOrder receives a matrix, an array of rows with m rows and n columns, and returns all its elements in spiral order. The walk starts at the top-left corner and goes clockwise around the outside: the top row from left to right, the right column from top to bottom, the bottom row from right to left, and the left column from bottom to top. Then it repeats on what is left inside, until every element has been visited exactly once.
For the matrix with rows [1, 2, 3, 4], [5, 6, 7, 8] and [9, 10, 11, 12], the outside gives 1, 2, 3, 4, 8, 12, 11, 10, 9, 5. What remains is a single row, 6 and 7, so the answer is [1, 2, 3, 4, 8, 12, 11, 10, 9, 5, 6, 7]. The statement expects O(m * n) time: each element is visited once.
Approach: shrinking boundaries
A first idea is to keep a row and column position plus a direction, and to turn whenever the next cell is outside the matrix or already visited. That needs a visited marker for every cell, or a rule for when to turn.
The lesson tracks the unvisited part with four numbers instead: top and bottom are its first and last rows, and left and right are its first and last columns. One lap of the loop walks the four sides of that part, and each finished side moves its boundary one step inward. The loop ends when a pair of boundaries crosses, because then nothing is left.
The delicate part is the end of the spiral. When one row or one column is left, the walk along the top (or right) side already visits everything, and the walk back along the opposite side would visit the same elements a second time. That is why the bottom row and the left column are each guarded by an if.
Here are the boundaries after each lap on the 3 by 4 example:
after lap 1: top=1 bottom=1 left=1 right=2
after lap 2: top=2 bottom=1 left=2 right=1
After the first lap the unvisited part is row 1, columns 1 to 2, which is the 6 and 7. The second lap walks the top side (6, 7). Both pairs then cross, so the if checks skip the bottom row and the left column, and the loop ends.
Step by step
- Create
result, an empty[Int]declared withvar, to collect the elements in visiting order. - Set the row boundaries:
topis 0 andbottomismatrix.count - 1. - Set the column boundaries:
leftis 0 andrightismatrix[0].count - 1. Every row has the same length, so the first row tells how many columns there are. - Loop while
top <= bottom && left <= right. While neither pair has crossed, some elements are still unvisited. - Walk the top row with
coloverleft...rightand appendmatrix[top][col]. The loop condition guaranteesleft <= righthere, so the closed range is valid. - Move
topdown. Doing it right away also keeps the top-right corner from being visited again by the next walk. - Walk the right column from
toptobottomand appendmatrix[row][right]. It is written withstridebecausetopmay already be pastbottom(a one-row matrix), andstridethen produces no values instead of failing. - Move
rightone column left. - Guard the bottom row with
if top <= bottom. If only one row was left, it was just walked as the top row. - Walk the bottom row backwards with
stride(from: right, through: left, by: -1), then movebottomup. - Guard the left column with
if left <= right. If only one column was left, it was just walked as the right column. - Walk the left column upwards from
bottomtotop, then moveleftto the right. That finishes the lap. - Return
resultafter the loop.
The solution in Swift
class Solution {
func spiralOrder(_ matrix: [[Int]]) -> [Int] {
var result = [Int]()
var top = 0, bottom = matrix.count - 1
var left = 0, right = matrix[0].count - 1
while top <= bottom && left <= right {
for col in left...right {
result.append(matrix[top][col])
}
top += 1
for row in stride(from: top, through: bottom, by: 1) {
result.append(matrix[row][right])
}
right -= 1
if top <= bottom {
for col in stride(from: right, through: left, by: -1) {
result.append(matrix[bottom][col])
}
bottom -= 1
}
if left <= right {
for row in stride(from: bottom, through: top, by: -1) {
result.append(matrix[row][left])
}
left += 1
}
}
return result
}
}
Swift details worth knowing:
left...rightagainststride. A closed rangea...bneedsa <= b, and Swift stops the program if it is not true. That is fine for the top row, where the loop condition guarantees it. For the other three walks the boundaries may have crossed, so the code usesstride, which is simply empty in that case. For example,stride(from: 2, through: 1, by: 1)gives no values.stride(from:through:by:)includes the end value, and a negative step counts down.- Declaring two variables on one line.
var top = 0, bottom = matrix.count - 1declares two separatevars of typeInt. var result = [Int]()creates an empty array, andappendadds one element at the end.- Empty input.
matrix[0]would be an index error for an empty matrix, which the constraints rule out (mis at least 1).
Complexity
Time: O(m * n). Each element is appended exactly once, and the boundary checks add a constant amount of work per lap. There are at most about half of min(m, n) laps.
Space: O(1) extra. Apart from the returned array, the method keeps four boundary variables and a loop variable.
Edge cases and common mistakes
- One row.
[[1, 2, 3]]gives[1, 2, 3]. After the top walk,topis pastbottom, so the right-column walk and the bottom-row guard produce nothing. - One column.
[[3], [2], [1]]gives[3, 2, 1]. The right column holds 2 and 1, and the guard on the left column keeps 2 and 1 from being added again. - A single cell.
[[7]]gives[7]. - Not square. The 3 by 2 matrix with rows
[1, 2],[3, 4]and[5, 6]gives[1, 2, 4, 6, 5, 3]. - Leaving out an
ifguard. The matrix[[1, 2, 3]]would give[1, 2, 3, 2, 1]without the first guard, since the row that was just walked as the top row would be read again as the bottom row. - Moving a boundary at the wrong time. The lesson moves each boundary right after its side is done, so the next side starts at the correct corner. Moving them all at the end of the lap would visit the corners twice.
- Using
...for the later walks. A matrix with one row would stop the program whentop...bottomhastopabovebottom.
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], [5, 6]]gives[1, 2, 4, 6, 5, 3].
