Matrix problems often look intimidating.
Too many rows, columns, indices…
But most interview questions are built on just a few core patterns.
Master these patterns once,
and matrix questions become much easier.
1. Spiral Traversal
Problem
Print matrix elements in spiral order.
public static List spiralOrder(int[][] matrix) {
List<Integer> result = new ArrayList<>();
int top = 0, bottom = matrix.length - 1; int left = 0, right = matrix[0].length - 1;
while (top <= bottom && left <= right) {
for (int i = left; i <= right; i++) result.add(matrix[top][i]);
top++;
for (int i = top; i <= bottom; i++) result.add(matrix[i][right]);
right--;
if (top <= bottom) { for (int i = right; i >= left; i--) result.add(matrix[bottom][i]);
bottom--; }
if (left <= right) { for (int i = bottom; i >= top; i--) result.add(matrix[i][left]);
left++; } }
return result;
Enter fullscreen mode
Exit fullscreen mode
}
Core Idea
Maintain 4 boundaries:
top
bottom
left
right
Move inward layer by layer.
2.…