Walk the grid matrix in a clockwise spiral and return its values in the order you visit them. Start at the top-left corner and go right along the top row, then down the right column, left along the bottom row and up the left column. Then repeat on the ring inside, until every cell has been visited exactly once.
The outer ring gives 2 4 6, 12 18, 16 14, 8. Only the centre 10 is left.
With only two rows, one lap covers everything: across the top, down to 2, then back along the bottom.
A single column is read straight down.
Constraints
m == matrix.lengthn == matrix[i].length1 <= m, n <= 10-100 <= matrix[i][j] <= 100Treat the matrix as rings. Each lap reads the top row, the right column, the bottom row and the left column of whatever is left.
There's no trick to find here: the answer is fully defined by the walk the statement describes, and every cell is read exactly once. The whole difficulty is bookkeeping. Where does each side start and stop, and when is a side empty?
Time O(m · n)Space O(1)
The full walkthrough and code are part of Premium