Spiral Matrix: the idea to remember.
Return all values of a rectangular matrix in clockwise spiral order.
The core insight
Traverse the top row, right column, bottom row and left column, shrinking the corresponding boundary after each side.
Why it works
Each pass consumes exactly the current outer layer. The remaining rectangle is the same smaller problem.
The mistake to avoid
Check bounds before the bottom and left sides so a single remaining row or column is not visited twice.
Commented Java solution
Use java.util.* imports and a surrounding solution class. Tree snippets assume the standard TreeNode definition; linked lists use ListNode and Clone Graph uses a Node with val and neighbors; Copy Random List uses Node with val, next and random. Read the input assumptions above.
List<Integer> spiralOrder(int[][] a) {
List<Integer> out = new ArrayList<>();
if (a.length == 0) return out;
int top = 0, bottom = a.length - 1, left = 0, right = a[0].length - 1;
while (top <= bottom && left <= right) {
for (int c = left; c <= right; c++) out.add(a[top][c]); top++;
for (int r = top; r <= bottom; r++) out.add(a[r][right]); right--;
if (top <= bottom) { for (int c = right; c >= left; c--) out.add(a[bottom][c]); bottom--; }
if (left <= right) { for (int r = bottom; r >= top; r--) out.add(a[r][left]); left++; }
}
return out;
}Make the next connection
Independent revision notes with credited Java references. Not affiliated with LeetCode or the source sheets.