Given a binary matrix where 0 represents water and 1 represents land, and connected ones form an island, count the total islands.

For example, consider the following image:

Total number of Islands

 
The above image highlights water in blue and land in gray in a 10 × 10 matrix. There are a total of five islands present in the above matrix. They are marked by the numbers 1–5 in the image below.

Total Islands

Practice this problem

 
The solution is inspired by finding the total number of connected components in a graph problem. The idea is to start Breadth–first search (BFS) from each unprocessed node and increment the island count. Each BFS traversal will mark all cells which make one island as processed. So, the problem reduces to finding the total number of BFS calls.

In each BFS traversal, start by creating an empty queue. Then enqueue the starting cell and mark it as processed. Next dequeue the front node, process all eight adjacent cells of the current cell, and enqueue each valid cell, which is land. Repeat this process till the queue is not empty.

We can find all the possible locations we can move to from the given location by using the array that stores the relative position of movement from any location. For example, if the current location is (x, y), we can move to (x + row[k], y + col[k]) for 0 <= k <= 7 using the following arrays:

int row[] = { -1, -1, -1, 0, 0, 1, 1, 1 }
int col[] = { -1, 0, 1, -1, 1, -1, 0, 1 }

So, from position (x, y), we can move to:

(x – 1, y – 1)
(x – 1, y)
(x – 1, y + 1)
(x, y – 1)
(x, y + 1)
(x + 1, y – 1)
(x + 1, y)
(x + 1, y + 1)

This can be implemented as follows in C++, Java, and Python:

C++


Download  Run Code

Output:

The total number of islands is 5

Java


Download  Run Code

Output:

The total number of islands is 5

Python


Download  Run Code

Output:

The total number of islands is 5

The time complexity of the proposed solution is O(M × N) and requires O(M × N) extra space, where M and N are dimensions of the matrix.

 
Exercise: Solve this problem using Depth–first search algorithm.