Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Number of Islands in Python
The Number of Islands problem involves counting connected components of land (represented by 1s) in a 2D grid surrounded by water (represented by 0s). An island is formed by connecting adjacent lands horizontally or vertically.
Consider this grid example ?
| 1 | 1 | 0 | 0 | 0 |
| 1 | 1 | 0 | 0 | 0 |
| 0 | 0 | 1 | 0 | 0 |
| 0 | 0 | 0 | 1 | 1 |
This grid contains three islands: one large island (blue), one single-cell island (orange), and one small island (pink).
Algorithm Overview
The solution uses Depth-First Search (DFS) to solve this problem ?
- Iterate through each cell in the grid
- When we find a land cell (1), increment the island counter
- Use DFS to mark all connected land cells as water (0) to avoid counting them again
- Continue until all cells are processed
Implementation
class Solution:
def numIslands(self, grid):
if len(grid) == 0:
return 0
n = len(grid)
m = len(grid[0])
islands = 0
for i in range(n):
for j in range(m):
if grid[i][j] == "1":
islands += 1
self.make_water(i, j, n, m, grid)
return islands
def make_water(self, i, j, n, m, grid):
# Check boundaries
if i < 0 or j < 0 or i >= n or j >= m:
return
# If already water, return
if grid[i][j] == "0":
return
# Mark current cell as water
grid[i][j] = "0"
# Explore all 4 directions
self.make_water(i + 1, j, n, m, grid) # Down
self.make_water(i - 1, j, n, m, grid) # Up
self.make_water(i, j + 1, n, m, grid) # Right
self.make_water(i, j - 1, n, m, grid) # Left
# Test the solution
solution = Solution()
grid = [
["1","1","0","0","0"],
["1","1","0","0","0"],
["0","0","1","0","0"],
["0","0","0","1","1"]
]
result = solution.numIslands(grid)
print(f"Number of islands: {result}")
Number of islands: 3
How It Works
The algorithm works in two phases ?
- Discovery Phase: When we find a land cell ("1"), we increment the island counter
- Marking Phase: We use DFS to mark all connected land cells as water ("0")
The make_water() method recursively explores all four directions (up, down, left, right) from the current cell, converting connected land cells to water.
Time and Space Complexity
| Complexity | Value | Explanation |
|---|---|---|
| Time | O(n × m) | Visit each cell once |
| Space | O(n × m) | Worst case: all cells are land (recursion depth) |
Conclusion
The Number of Islands problem is efficiently solved using DFS to identify and mark connected components. The algorithm counts each island once and uses the "sink the island" technique to avoid recounting connected land cells.
