Number of Islands
Problem Statement
Given an m x n 2D binary grid grid which represents a map of '1's (land) and '0's (water), return the number of islands. An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water.
Constraints:
- m == grid.length
- n == grid[i].length
- 1 <= m, n <= 300
- grid[i][j] is '0' or '1'
Input Format:
- A 2D grid map where '1' represents land and '0' represents water
Output Format:
- Return the number of islands in the grid.
Examples:
Example 1:
Input:
grid = [ ['1','1','1','1','0'], ['1','1','0','1','0'], ['1','1','0','0','0'], ['0','0','0','0','0'] ]
Output:
1
Explanation:
There is only one island in the grid above.
Example 2:
Input:
grid = [ ['1','1','0','0','0'], ['1','1','0','0','0'], ['0','0','1','0','0'], ['0','0','0','1','1'] ]
Output:
3
Explanation:
There are three islands in the grid above.
Solutions
Depth-First Search Approach
Use DFS to traverse and mark visited lands. Each time we encounter a new unvisited land, we increment our count and use DFS to mark all connected lands as visited.
Breadth-First Search Approach
Use BFS to traverse and mark islands. For each unvisited land cell, increment the island count and use BFS to visit all connected land cells.
Algorithm Walkthrough
Example input: nums = []
Step-by-step execution:
- Starting BFS from grid[0][0] = '1':
- Mark (0,0) as visited and add to queue
- Explore neighbors of (0,0): mark (0,1) and (1,0) as visited
- Continue BFS until all connected land cells are visited
- This forms island #1
- Starting BFS from grid[2][2] = '1':
- Mark (2,2) as visited, no adjacent land cells
- This forms island #2
- Starting BFS from grid[3][3] = '1':
- Mark (3,3) as visited and add to queue
- Explore neighbors: mark (3,4) as visited
- This forms island #3
- No more unvisited land cells, return count = 3
Hints
Hint 1
Hint 2
Hint 3
Video Tutorial
Video tutorials can be a great way to understand algorithms visually
Visualization
Visualize the grid and the BFS/DFS traversal process for finding islands.
Key visualization elements:
- current cell
- visited cells
- island boundaries
- water
Implementation Notes
This problem is a classic example of graph traversal. It's important to understand both DFS and BFS approaches as they can be applied to many similar problems.