MediumNo. 0200
Number of Islands — LeetCode 200 Python Solution
- Pattern
- Union-Find
- Topics
- Depth-First Search, Breadth-First Search, Union Find, Array, Matrix
- On study lists
- Blind 75, NeetCode 150, Grind 75 and Top Interview 150
- Reading time
- 3 min
- Source
- leetcode.com
The problem
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.
Example
- Input
- grid = [
- Output
- 1
Python solution
class Solution:
def numIslands(self, grid: List[List[str]]) -> int:
def dfs(i, j):
grid[i][j] = '0'
for a, b in pairwise(dirs):
x, y = i + a, j + b
if 0 <= x < m and 0 <= y < n and grid[x][y] == '1':
dfs(x, y)
ans = 0
dirs = (-1, 0, 1, 0, -1)
m, n = len(grid), len(grid[0])
for i in range(m):
for j in range(n):
if grid[i][j] == '1':
dfs(i, j)
ans += 1
return ansComplexity
- Time
- O(m × n)
- Space · auxiliary
- O(m × n)
Pattern: Union-Find
Merge groups and ask whether two things are connected, both in near-constant time. LeetCode 200. Number of Islands is filed here because LeetCode tags it Union Find, which is the vocabulary this hub collects.
The union-find guide has the Python template for the pattern and the 83 LeetCode problems that use it.
Related problems
| No. | Problem | Difficulty |
|---|---|---|
| 0130 | Surrounded Regions | Medium |
| 0695 | Max Area of Island | Medium |
| 0827 | Making A Large Island | Hard |
| 1020 | Number of Enclaves | Medium |
| 1254 | Number of Closed Islands | Medium |
| 1267 | Count Servers that Communicate | Medium |
Frequently asked questions
- How hard is LeetCode 200. Number of Islands?
LeetCode 200. Number of Islands is rated Medium on LeetCode.
- What is the time complexity of LeetCode 200. Number of Islands?
The Python solution on this page runs in O(m × n).
- What is the space complexity of LeetCode 200. Number of Islands?
The Python solution on this page uses O(m × n) auxiliary space.
- What topics does LeetCode 200. Number of Islands cover?
LeetCode 200. Number of Islands is tagged Depth-First Search, Breadth-First Search, Union Find, Array and Matrix on LeetCode.