Problem overview
The function spiralOrder receives a matrix with m rows and n columns, as a [][]int, and returns all its elements in spiral order. The spiral starts at the top-left corner and goes clockwise around the outside: the top row left to right, the right column top to bottom, the bottom row right to left and the left column bottom to top. Then it repeats on what is left inside, until every element has been visited exactly once.
For the 3 by 3 matrix with rows [1, 2, 3], [4, 5, 6] and [7, 8, 9], the result is [1, 2, 3, 6, 9, 8, 7, 4, 5]. The outside ring gives 1, 2, 3, 6, 9, 8, 7, 4, and only 5 remains in the middle. The matrix doesn't have to be square: for three rows and four columns, the result is [1, 2, 3, 4, 8, 12, 11, 10, 9, 5, 6, 7], where the middle part is the single row 6, 7.
Approach: walk lap by lap and move the boundaries in
Tracking which cells were visited, say with a second matrix of booleans and a direction that turns when it hits a visited cell, works but costs O(m * n) extra space. There is a simpler way to see the problem.
Keep four numbers that describe the part not visited yet: top and bottom are its first and last rows, left and right its first and last columns. Each lap of the loop walks once around that part, clockwise, and every side that is finished moves its boundary one step inward. When a pair of boundaries crosses, nothing is left.
The tricky part is that the inner part can shrink to a single row or a single column. The four sides then overlap, and walking all four would visit some elements twice. Two checks, one before the bottom side and one before the left side, prevent it.
Without those checks, the 3 by 4 example would return [1, 2, 3, 4, 8, 12, 11, 10, 9, 5, 6, 7, 6], with an extra 6 at the end. A single column [3], [2], [1] would return [3, 2, 1, 2].
Step by step
- Start an empty
resultslice. It collects the elements in the order the spiral visits them. - Declare the row boundaries:
topis 0 andbottomislen(matrix)-1. - Declare the column boundaries:
leftis 0 andrightislen(matrix[0])-1. Every row has the same length, so the first row tells the column count. - Loop while
top <= bottom && left <= right. While neither pair has crossed, some elements are unvisited, and each pass walks around them. - Walk the top row from
lefttoright, both included, appendingmatrix[top][col]each time. - Move
topdown by one. The top row is done. Moving it before the next side also keeps the top-right corner from being visited again. - Walk the right column from the new
toptobottom, appendingmatrix[row][right]. - Move
rightone column to the left. - Check
top <= bottom. If only one row was left, it was just walked as the top row, andtophas passedbottom. Walking it back would add it twice. - Inside the check, walk the bottom row from
rightdown toleft, appendingmatrix[bottom][col], then movebottomup by one. - Check
left <= right. If only one column was left, it was just walked as the right column, andrighthas passedleft. - Inside that check, walk the left column from
bottomup totop, appendingmatrix[row][left], then moveleftone column to the right. That ends the lap. - Return
resultafter the outer loop.
The solution in Go
func spiralOrder(matrix [][]int) []int {
result := []int{}
top, bottom := 0, len(matrix)-1
left, right := 0, len(matrix[0])-1
for top <= bottom && left <= right {
for col := left; col <= right; col++ {
result = append(result, matrix[top][col])
}
top++
for row := top; row <= bottom; row++ {
result = append(result, matrix[row][right])
}
right--
if top <= bottom {
for col := right; col >= left; col-- {
result = append(result, matrix[bottom][col])
}
bottom--
}
if left <= right {
for row := bottom; row >= top; row-- {
result = append(result, matrix[row][left])
}
left++
}
}
return result
}
The Go details worth a closer look:
appendreturns the slice. It may have to allocate a bigger backing array, so its result is always assigned back:result = append(result, ...). Callingappendand ignoring the return value would lose the new element. Because the loops add each element once, the slice grows in amortized constant time per element.result := []int{}starts an empty slice ofintwith length 0, ready forappend.- Multiple declaration.
top, bottom := 0, len(matrix)-1declares two variables in one statement. - Go's while loop. The outer
forhas only a condition. Go has nowhilekeyword, andfor condition { ... }plays its role. - Down-counting loops.
col--androw--are fine because the variables are signedints, and the conditioncol >= leftstops them as soon as they drop below the boundary. - Indexing a missing row panics.
matrix[0]needs at least one row. The constraints guaranteemandnare at least 1.
Complexity
Time: O(m * n). Each element is appended exactly once, and the loops do no other work beyond moving the boundaries.
Space: O(1) extra, beyond the returned slice of m * n elements. The only variables are the four boundaries and the loop counters.
Edge cases and common mistakes
- A single row.
[[1, 2, 3]]gives[1, 2, 3]. After the top row,topis 1 andbottomis 0, so the first check skips the bottom row. - A single column.
[[3], [2], [1]]gives[3, 2, 1]. After the right column,rightis -1 andleftis 0, so the second check skips the left column. - A single element.
[[7]]gives[7]. - A 2 by 2 matrix.
[[1, 2], [3, 4]]gives[1, 2, 4, 3]. Both checks pass, and the lap uses all four sides once. - Forgetting the two checks. The result then repeats elements whenever the inner part is one row or one column wide, as shown above.
- Using
<in the loops. Both ends of every side are elements to visit, so each side's loop uses<=or>=. - Moving the boundary too late. If
top++comes after the right-column loop, the top-right corner is appended 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].[[7]]gives[7].
