Back to Main
Learn DSA
Depth-First Search
Greedy Algorithms
Get Premium
Depth-First Search
Number of Islands
medium
DESCRIPTION (credit Leetcode.com)
You are given binary matrix grid of size m x n, where '1' denotes land and '0' signifies water. Determine the count of islands present in this grid. An island is defined as a region of contiguous land cells connected either vertically or horizontally, and it is completely encircled by water. Assume that the grid is bordered by water on all sides.
Input:
Output:
Explanation
This solution uses depth-first search to traverse the grid and count the number of islands.
The algorithm starts at the first cell of the grid and explores all the adjacent cells that are part of the same island. To be part of the same island, a cell must be a 1 and must be adjacent to the current cell. During each recursive call, the algorithm first marks the current cell by changing its value to 0 so that it does not explore the same cell again.
We'll walkthrough how the algorithm detects 2 islands in the example grid:
[
[1, 1, 0, 1],
[1, 1, 0, 1],
[1, 1, 0, 0]
]
First Island
The algorithm starts by iterating over all cells in the grid. If it finds a 1, it increments the count variable and starts the depth-first search exploration from that cell. The algorithm explores all the reachable cells of the island, marking them as "0" so that it does not explore them again.
Python
i = 0
0 / 19
1x
Once the algorithm has explored all reachable cells of the island, it iterates over the remaining cells to find the start of the next island. When it finds a "1", it increments the count variable and starts the depth-first search exploration again from that cell, this time exploring all the reachable cells of the new island.
Second Island
Once the first call to dfs has returned, the algorithm continues iterating over the remaining cells. When it finds another cell with value of 1, then this is start of a new island.
Python
recursive call
0 / 9
1x
The algorithm continues this process until it has explored all the cells of the grid, at which point it returns the count variable, which contains the number of islands.
Animated Solution
Python
number of islands
0 / 46
1x
Login to track your progress
Your account is free and you can post anonymously if you choose.