To solve the "Matrix Spiral Traversal" problem, we need to traverse the 2D matrix in a spiral order starting from the top-left corner and moving clockwise until we cover all elements. We can do this by maintaining boundaries for the rows and columns and iterating over them in the required order (right, down, left, up), adjusting the boundaries after each pass.
Here's how you can implement it in Python:
from typing import List
def spiral_traversal(matrix: List[List[int]]) -> List[int]:
if not matrix or not matrix[0]:
return []
result = []
top, bottom = 0, len(matrix) - 1
left, right = 0, len(matrix[0]) - 1
while top <= bottom and left <= right:
# Traverse from left to right along the top row
for i in range(left, right + 1):
result.append(matrix[top][i])
top += 1
# Traverse downwards along the right column
for i in range(top, bottom + 1):
result.append(matrix[i][right])
right -= 1
if top <= bottom:
# Traverse from right to left along the bottom row
for i in range(right, left - 1, -1):
result.append(matrix[bottom][i])
bottom -= 1
if left <= right:
# Traverse upwards along the left column
for i in range(bottom, top - 1, -1):
result.append(matrix[i][left])
left += 1
return result
# Example usage
print(spiral_traversal([[1, 2, 3], [4, 5, 6], [7, 8, 9]])) # Output: [1, 2, 3, 6, 9, 8, 7, 4, 5]
print(spiral_traversal([[1, 2], [3, 4]])) # Output: [1, 2, 4, 3]
print(spiral_traversal([[1]])) # Output: [1]
print(spiral_traversal([[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]
Explanation:
-
Initialize Boundaries:
top and bottom track the row boundaries.
left and right track the column boundaries.
-
Iteration:
- Left to Right: Add top row elements from the
left to right, then move the top boundary downward.
- Top to Bottom: Add right column elements from the
top to bottom, then move the right boundary leftward.
- Right to Left: If there's still space, add bottom row elements from the
right to left, then move the bottom boundary upward.
- Bottom to Top: If there's still space, add left column elements from the
bottom to top, then move the left boundary rightward.
-
Termination:
- The loops break when
top > bottom or left > right, meaning we've visited all elements.
This approach guarantees we cover all elements in the correct spiral order with O(m*n) complexity, where m and n are the matrix dimensions.