Spiral Matrix Problem
Description
LeetCode Problem 54.
Given an m x n matrix, return all elements of the matrix in spiral order.
Example 1:
Input: matrix = [[1,2,3],[4,5,6],[7,8,9]]
Output: [1,2,3,6,9,8,7,4,5]
Example 2:
Input: matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]
Output: [1,2,3,4,8,12,11,10,9,5,6,7]
Constraints:
- m == matrix.length
- n == matrix[i].length
- 1 <= m, n <= 10
- -100 <= matrix[i][j] <= 100
Solution
Approach: Shrinking Boundaries
Walk the matrix the way the spiral goes, one layer at a time from the outside in. Keep four boundaries for the part not visited yet: top and bottom rows, left and right columns. Each round walks the outer ring of that rectangle and then shrinks it:
- Top row, left to right, then
top++. - Right column, top to bottom, then
right--. - Bottom row, right to left, then
bottom--. - Left column, bottom to top, then
left++.
Repeat while top <= bottom and left <= right.
The detail people get wrong is the last ring when only one row or one column is left. For [[1, 2, 3]], step 1 reads 1, 2, 3 and moves top below bottom; without a check, step 3 would read the same row again backwards. So steps 3 and 4 run only if a row (top <= bottom) or a column (left <= right) is still left. Steps 1 and 2 need no check: the loop condition covers step 1, and step 2's loop simply does nothing when top > bottom.
1 → 2 → 3
↓
4 → 5 6 order: 1 2 3 6 9 8 7 4 5
↑ ↓
7 ← 8 ← 9
Complexity: O(m · n) time, where m and n are the numbers of rows and columns (each cell is read once), and O(1) extra space besides the output.
class Solution:
def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
result = []
# The rows and columns not visited yet.
top, bottom = 0, len(matrix) - 1
left, right = 0, len(matrix[0]) - 1
while top <= bottom and left <= right:
for col in range(left, right + 1): # top row, left to right
result.append(matrix[top][col])
top += 1
for row in range(top, bottom + 1): # right column, top to bottom
result.append(matrix[row][right])
right -= 1
if top <= bottom: # bottom row, right to left, if a row is left
for col in range(right, left - 1, -1):
result.append(matrix[bottom][col])
bottom -= 1
if left <= right: # left column, bottom to top, if a column is left
for row in range(bottom, top - 1, -1):
result.append(matrix[row][left])
left += 1
return result
Now write it from memory
Close the write-up and solve it yourself against the tests.