Loading problem...
You are given a two-dimensional grid of integers represented as an m × n matrix. Your task is to traverse the grid in a clockwise spiral pattern starting from the top-left corner, and return all elements in the order they are visited.
The spiral traversal works as follows:
Imagine peeling an onion layer by layer from the outside — you traverse the outermost boundary first, then progressively work your way inward toward the center of the grid.
matrix = [[1,2,3],[4,5,6],[7,8,9]][1,2,3,6,9,8,7,4,5]Starting from top-left (1), we traverse right along the first row (1→2→3), then down the right column (6→9), then left along the bottom row (8→7), then up the left column (4), and finally the center element (5). The spiral path covers all 9 elements.
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]For this 3×4 matrix, we first traverse the outer boundary clockwise: top row (1→2→3→4), right column (8→12), bottom row (11→10→9), left column (5). Then the inner elements (6→7) are traversed left-to-right as they form the remaining unvisited row.
matrix = [[1,2],[3,4]][1,2,4,3]For this small 2×2 grid, the spiral is simply: right across top (1→2), down right column (4), left across bottom (3). All 4 elements visited in one spiral layer.
Constraints