Peeling an onion layer by layer, or reading a newspaper column by column: you need clear rules for where to turn.
Clues that point here
→ 2D array or grid input
→ Spiral order
→ Rotate an image
→ Set rows/columns to zero
→ Neighbours up, down, left, right
Not this pattern when
✕ You need shortest paths or connected regions on the grid (BFS/DFS)
The template
A skeleton to adapt. The parts in comments are what changes from problem to problem.
Matrix Traversal · template
int[][] dirs = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; // right, down, left, up
for (int r = 0; r < rows; r++) {
for (int c = 0; c < cols; c++) {
for (int[] d : dirs) {
int nr = r + d[0], nc = c + d[1];
if (nr < 0 || nc < 0 || nr >= rows || nc >= cols) continue; // off the grid
visit(grid[nr][nc]);
}
}
}