MediumNo. 0200

Number of Islands — LeetCode 200 Python Solution

Pattern
Union-Find
Topics
Depth-First Search, Breadth-First Search, Union Find, Array, Matrix
Reading time
3 min

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

PythonSolution
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 ans

Complexity

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

Related problems
No.ProblemDifficulty
0130Surrounded RegionsMedium
0695Max Area of IslandMedium
0827Making A Large IslandHard
1020Number of EnclavesMedium
1254Number of Closed IslandsMedium
1267Count Servers that CommunicateMedium

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.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity, invisible to screen sharing.

Free to download. Check it runs on your machine, then pick a plan.