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.