Return all the elements of a matrix in spiral order. Go right along the top, down the right side, left along the bottom, and up the left side, then repeat inward.
DSA Animator › DSA Revision › Matrix › Spiral Matrix
Remember: four boundaries, four walks, shrink after each. Re-check the boundaries before walking back. The video solves Spiral Matrix (LeetCode 54, Medium) with the Boundary Traversal pattern from the Matrix topic, and you can replay every step in the interactive Spiral Matrix animation.
Return all the elements of a matrix in spiral order. Go right along the top, down the right side, left along the bottom, and up the left side, then repeat inward.
For this 3 by 4 matrix, the spiral order is 1, 2, 3, 4, 8, 12, 11, 10, 9, 5, 6, 7.
Simulating with a direction and a visited grid works, but needs extra space and careful turning rules. Four shrinking boundaries are simpler.
Keep four boundaries: top, bottom, left and right. Walk the top row, then move top down. Walk the right column, then move right in, and do the same for the bottom row and the left column. Before the bottom and left walks, check that the boundaries have not crossed.
Walk the top row: 1, 2, 3, 4. Walk down the right column: 8 and 12. Walk the bottom row backwards: 11, 10, 9. Walk up the left column: 5. Now only the middle row is left: 6 and 7. The boundaries cross, so we stop with 12 numbers.
In code, set the four boundaries. While top is not below bottom and left is not past right, walk the four sides. After each side, move that boundary inward. Check the boundaries again before the bottom row and the left column, so a single row or column is not read twice. Every element is visited once, so it's O of m times n time.
Remember: four boundaries, four walks, shrink after each. Re-check the boundaries before walking back.