Exploring a cave system with a ball of string: follow one tunnel to its end before coming back to try the next.
Clues that point here
→ Count islands or connected components
→ Flood fill, surrounded regions
→ Can you reach X from Y?
→ Clone a graph
Not this pattern when
✕ You need the shortest path (BFS)
The template
A skeleton to adapt. The parts in comments are what changes from problem to problem.
Graph DFS and Flood Fill · template
void dfs(char[][] grid, int r, int c) {
if (r < 0 || c < 0 || r >= grid.length || c >= grid[0].length) return;
if (grid[r][c] != '1') return; // water or already visited
grid[r][c] = '#'; // mark visited
dfs(grid, r + 1, c); dfs(grid, r - 1, c);
dfs(grid, r, c + 1); dfs(grid, r, c - 1);
}