Spiral Matrix
Medium· simulation· boundaries
Problem
Return all elements of an m × n matrix in spiral order: across the top row, down the right column, back along the bottom row, up the left column, then repeat inward.
Examples
Input: matrix = [[1,2,3],[4,5,6],[7,8,9]]
Output: [1,2,3,6,9,8,7,4,5]
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
- • 1 <= m, n <= 10
- • -100 <= matrix[i][j] <= 100
Hints & approach
Hint 1
Keep four boundaries: top, bottom, left, right.
Hint 2
After finishing a side, move that boundary inward.
Hint 3
Re-check the boundaries before walking the bottom row and left column to avoid repeats on thin matrices.
Approachtry the hints first
Maintain top, bottom, left and right bounds. Walk the top row left to right and increment top; walk the right column top to bottom and decrement right. If top ≤ bottom, walk the bottom row right to left and decrement bottom; if left ≤ right, walk the left column bottom to top and increment left. Stop when the bounds cross.
Time O(m·n) · Space O(1) besides the output