PythonMediumMatrices20 min
Traverse a matrix in spiral order
Consume the outer perimeter before moving inward. Every cell must appear exactly once, including in one-row or one-column matrices. Interviewers use this problem to assess maintain four boundaries and guard the remaining bottom and left sides.
Input
First line: rows and columns. Next rows lines: columns integers each.
Output
Print the result values separated by single spaces; print an empty line for an empty result.
Constraints
1 <= rows, columns <= 300; -10^9 <= entries <= 10^9.
Example
Input
3 3 1 2 3 4 5 6 7 8 9
Output
1 2 3 6 9 8 7 4 5
Example 2 input
2 2 0 0 -1 -1
Output
0 0 -1 -1
Repeated values are separate cells, not duplicates to remove.
Public test cases (2)
Input
3 3 1 2 3 4 5 6 7 8 9
Expected output
1 2 3 6 9 8 7 4 5
Input
2 3 1 2 3 4 5 6
Expected output
1 2 3 6 5 4
Hints (2)
- Identify the state needed to avoid repeated work.
- Maintain four boundaries and guard the remaining bottom and left sides.
Target complexity: time O(rows * columns) · space O(rows * columns) for the result
