NeetCode #902LC-54MediumMath & GeometryBlind 75NC 150NC 250
← Back to All Problems#902 · #54 · Spiral Matrix(螺旋矩阵)
📌 Problem Statement & Constraints
Given an
m x n matrix, return all of its elements in spiral order, starting at the top-left and moving clockwise inward. Constraints: 1 <= m, n <= 10, -100 <= matrix[i][j] <= 100.💡 Core Algorithmic Approaches
- Maintain four boundaries --
top,bottom,left,right-- and peel the matrix one layer at a time. - Traverse 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, shrinking the corresponding boundary after each pass.
- The two
ifguards before the bottom-row and left-column passes are essential: in a layer with a single remaining row or column they prevent elements from being emitted twice. - The loop terminates when the boundaries cross, at which point every cell has been appended exactly once.
💻 Benchmark Python3 Implementation
class Solution:
def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
res = []
top, bottom = 0, len(matrix) - 1
left, right = 0, len(matrix[0]) - 1
while top <= bottom and left <= right:
for j in range(left, right + 1): # top row, left -> right
res.append(matrix[top][j])
top += 1
for i in range(top, bottom + 1): # right column, top -> bottom
res.append(matrix[i][right])
right -= 1
if top <= bottom: # guard: a row still remains
for j in range(right, left - 1, -1):
res.append(matrix[bottom][j])
bottom -= 1
if left <= right: # guard: a column still remains
for i in range(bottom, top - 1, -1):
res.append(matrix[i][left])
left += 1
return res⚡ Complexity Deep Dive
⏱️ Time Complexity
O(m * n): each cell is appended exactly once.
💾 Space Complexity
O(1) beyond the output list.
⚠️ Interview Pitfalls & Follow-ups
- Omitting the two boundary guards: for a single-row layer the bottom-row pass re-appends the row just emitted, and for a single-column layer the left-column pass duplicates the column.
- Shrinking a boundary before traversing its side: the boundary must be updated only after its side is fully consumed.
- Using
range(left, right)without+1: the right boundary is inclusive, soright + 1is required. - Assuming a square matrix:
mandndiffer in general, so the two dimensions must be tracked separately.