Medium · Boundary Simulation
Understand → Visualise → Practice.
Return all matrix values in clockwise spiral order, beginning at the top-left cell.
Keep four boundaries. Read the top row, right column, bottom row and left column, shrinking the boundary after each side.
top, bottom, left and right start at the matrix edges.
Top row left to right, right column downwards, bottom row right to left, left column upwards.
Only walk the bottom row and left column if top ≤ bottom and left ≤ right.
O(rows × cols) time and O(1) extra space.
Without boundary checks, the final single row or column is visited twice.
Read the full guide first: Matrices and 2-D Arrays.
Guest mode lets you understand, visualise and run the sample tests. Create a free account to submit and save your solutions.