JavaHardMatrices35 min
Traverse a matrix in spiral order
Print a clockwise spiral traversal starting at the top-left corner, space-separated. Follow the stated ordering and edge-case conventions exactly. Interviewers use this task to probe algorithm selection, invariants, and boundary handling.
Input
rows cols followed by rows*cols integers in row-major order.
Output
Print a clockwise spiral traversal starting at the top-left corner, space-separated.
Constraints
1 <= rows,cols <= 300; values in [-1000000000,1000000000].
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
This example exercises a further boundary or ordering case.
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 recomputing work for each element.
- Shrink four boundaries after visiting each side, checking that the remaining rows and columns still exist.
Target complexity: time O(rows*cols) · space O(rows*cols)
