πΆExplain Like I'm 5
ποΈ Real-Life Example: Counting Islands from a Helicopter
You're flying over an ocean looking down at a grid map. Green squares π© are land, blue squares π¦ are water. An island is made of land squares that TOUCH each other (up, down, left, right - NOT diagonal corners).
π Step 1: Scan the Map
Start at top-left, go row by row, checking every square like reading a book.
ποΈ Step 2: When You Find New Land
- Say "Found island #1!" and increment counter
- Paint it: Use DFS to explore and mark ALL connected land
- How DFS Works: From current land, explore up, down, left, right recursively until you hit water or already-painted land
π¨ Step 3: Keep Scanning
Continue scanning the grid. Already-painted land won't trigger a new island count. Each NEW unpainted land = new island!
π‘ Key Insight: DFS explores deeply like following a trail in a maze - go as far as you can in one direction before backtracking. This ensures you find ALL connected land pieces in one island before moving to the next!
β‘ Why DFS? It naturally explores all connected components (islands) by exhaustively following each path until hitting a boundary (water)!
π Code Debugger
π Variables:
πΊοΈ Island Grid
Click "Start" to begin island detection
β Complete Java Solution
DFS + Graph Patternpublic int numIslands(char[][] grid) {
int count = 0;
for (int r = 0; r < grid.length; r++) {
for (int c = 0; c < grid[0].length; c++) {
if (grid[r][c] == '1') {
count++; // Found new island!
dfs(grid, r, c); // Mark all connected land
}
}
}
return count;
}
private void dfs(char[][] grid, int r, int c) {
// Base case: out of bounds or water
if (r < 0 || c < 0 || r >= grid.length ||
c >= grid[0].length || grid[r][c] == '0') {
return;
}
grid[r][c] = '0'; // Mark as visited (sink the land)
// Explore all 4 directions
dfs(grid, r + 1, c); // Down
dfs(grid, r - 1, c); // Up
dfs(grid, r, c + 1); // Right
dfs(grid, r, c - 1); // Left
}
// Time: O(rows Γ cols), Space: O(rows Γ cols) for recursion