Problem overview
The method spiralOrder takes a matrix as an Array[Array[Int]] with m rows and n columns, and returns an ArrayBuffer[Int] holding all of its elements in spiral order. The spiral starts at the top-left corner and goes clockwise: along the top row, down the right column, back along the bottom row, and up the left column. Then it repeats on what is left inside, until every element has been visited exactly once.
For this matrix:
1 2 3
4 5 6
7 8 9
the result is [1,2,3,6,9,8,7,4,5]: the outer ring clockwise, then the single cell 5 in the middle. For the 3 by 4 matrix with rows 1,2,3,4, 5,6,7,8 and 9,10,11,12 the result is [1,2,3,4,8,12,11,10,9,5,6,7]. The second lap there is a single row, 6 and 7.
Approach: walk the sides and move the boundaries inward
Computing each element's position directly is awkward, because the direction changes at every corner. A cleaner way is to remember which part of the matrix has not been visited yet. Four variables describe it: top and bottom are its first and last unvisited rows, and left and right are its first and last unvisited columns.
One lap walks the four sides of that rectangle. After each side is finished, the matching boundary moves one step inward, so the next lap works on a smaller rectangle. When a pair of boundaries crosses, nothing is left and the loop stops. Each element is added once, so the work is proportional to the number of elements.
The tricky part is the end of the spiral. When the rectangle is a single row or a single column, the bottom side or the left side would walk the same elements a second time. The two if checks in the solution prevent that.
Step by step
- Create
resultas an emptyArrayBuffer[Int]in aval. It collects the elements in visiting order, and thevalis fine because the buffer itself changes, not the name. - Row boundaries:
topstarts at 0 andbottomatmatrix.length - 1. They arevars because they move. - Column boundaries:
leftstarts at 0 andrightatmatrix(0).length - 1. Every row has the same length, so the first row says how many columns there are. - Loop while
top <= bottom && left <= right. As long as neither pair has crossed, some elements remain. - Top side:
for (col <- left to right)appendsmatrix(top)(col)toresultwith+=. - Move
topdown. The top row is done. Doing it right here also stops the top-right corner from being read again by the next side. - Right side:
for (row <- top to bottom)appendsmatrix(row)(right). - Move
rightleft. The right column is done. - Guard the bottom side with
if (top <= bottom). If only one row was left, the top-side loop already read it, andtophas moved pastbottom. Reading it backwards would add its elements twice. - Bottom side:
for (col <- right to left by -1)appendsmatrix(bottom)(col), thenbottommoves up. - Guard the left side with
if (left <= right). With a single column left, the right side already covered it (the 3 by 1 example), and walking up would repeat it. - Left side:
for (row <- bottom to top by -1)appendsmatrix(row)(left), thenleftmoves right. That ends the lap. - Return
result.
The solution in Scala
class Solution {
def spiralOrder(matrix: Array[Array[Int]]): ArrayBuffer[Int] = {
val result = ArrayBuffer[Int]()
var top = 0
var bottom = matrix.length - 1
var left = 0
var right = matrix(0).length - 1
while (top <= bottom && left <= right) {
for (col <- left to right) {
result += matrix(top)(col)
}
top += 1
for (row <- top to bottom) {
result += matrix(row)(right)
}
right -= 1
if (top <= bottom) {
for (col <- right to left by -1) {
result += matrix(bottom)(col)
}
bottom -= 1
}
if (left <= right) {
for (row <- bottom to top by -1) {
result += matrix(row)(left)
}
left += 1
}
}
return result
}
}
Scala details worth knowing:
ArrayBufferneeds an import. It lives inscala.collection.mutable, so a standalone file that uses it needsimport scala.collection.mutable.ArrayBufferat the top. Unlike anArray, anArrayBuffergrows, and+=appends one element.toincludes its end, and an empty range is fine.left to rightcovers both columns. When the start is past the end, as in3 to 2, the range is empty and the loop body never runs. The solution relies on this when the rectangle has run out of rows or columns. A range that counts down needsby -1:2 to 0 by -1gives 2, 1, 0, but2 to 0alone is empty.- The loop bounds are read once. A
forover a range evaluatesleft to rightwhen the loop starts. Changingtoporrightinside the loop wouldn't change the range already in progress, which is why the code moves them after each loop. - Explicit
return. The reference ends withreturn result. In Scala the last expression alone,result, would give the same value, andreturnis rarely needed, but it is correct here. - The result type. The method returns an
ArrayBuffer[Int], not anArray. Printing it withmkString("[", ",", "]")gives the format of the examples.
Complexity
Time: O(m * n). Every element is appended exactly once, and the loops do a constant amount of work apart from those appends. The boundary checks add only a few operations per lap.
Space: O(1) extra. Besides the returned buffer, which holds all m * n elements, only the four boundary variables and the loop counters are stored.
Edge cases and common mistakes
- A single row.
[[1,2,3]]gives[1,2,3]. The top side reads everything,topmoves pastbottom, and the two guards skip the remaining sides. - A single column.
[[3],[2],[1]]gives[3,2,1]. The top side reads 3, and the right side reads 2 and 1. Thenleft <= rightis false, so nothing is read twice. - A single element.
[[4]]gives[4]. - A tall matrix. The 4 by 2 matrix with rows
1,2,3,4,5,6and7,8gives[1,2,4,6,8,7,5,3]. The left side stops before the top row, so 1 isn't visited again. - Dropping the two
ifguards. On any matrix whose last lap is a single row or column, elements would appear twice. - Using
untilin place ofto. The boundaries are inclusive indices of rows and columns, sountilwould leave out the last one. - Forgetting
by -1.right to leftis empty whenrightis bigger thanleft, so the bottom and left sides would silently add nothing. - Empty input. The lesson guarantees at least one row and one column.
matrix(0)would throw an exception on an array with no rows.
Testing
- The 3 by 3 matrix above gives
[1,2,3,6,9,8,7,4,5]. - The 3 by 4 matrix above 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].[[4]]gives[4].- The 4 by 2 matrix above gives
[1,2,4,6,8,7,5,3].
