Given an m × n matrix, return all elements of the matrix in spiral order (clockwise from the top-left).
matrix = [[1,2,3],[4,5,6],[7,8,9]][1,2,3,6,9,8,7,4,5]matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12]][1,2,3,4,8,12,11,10,9,5,6,7]matrix = [[1]][1]top=0, bottom=m-1, left=0, right=n-1top++right--top≤bottom); then bottom--left≤right); then left++top≤bottom && left≤rightInstead of tracking visited cells, we use four integer boundaries that shrink inward after each directional pass. This guarantees every cell is visited exactly once in spiral clockwise order, with O(1) extra space.
The if (top<=bottom) and if (left<=right) guards prevent double-counting the last row or column when the spiral collapses to a single row/column.
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.
Four boundaries, four walks, shrink after each. Re-check the boundaries before walking back.
Run the animation above on your own input, or watch the 1:30 video explanation of Spiral Matrix with a dry run and Java code.