Number of Islands

In this tutorial, I am going to discuss a very famous interview problem. How to count the number of islands.

Given a 2d grid map of ‘1’s (land) and ‘0’s (water), count the number of islands. An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically.

You may assume all four edges of the grid are surrounded by water.

Number of Islands LeetCode Solution

Now, The important question is how do we approach this problem. In this tutorial, I am going to explain the number of islands LeetCode solution using BFS and DFS technique and its java code.

At the end of this post, I have shared a video tutorial link.

Programming Video Tutorials

Count Number of Islands using DFS (Depth First Search) – Java Code

In this example, I am going to explain how to solve this problem using DFS (Depth First Search).

The first step is to traverse a matrix. When we found a grid whose value is 1 then check all the connected 1’s and mark them as visited. After doing this increment the count which keeps track of the no. of islands.

Repeat this process until the matrix is traversed completely.

The time complexity of this approach is O(n*m) where n is the no of rows and m is the no. of columns.

Number of islands DFS video tutorial

Count Number of Islands using BFS (Breadth First Search) – Java Code

In our previous example, we have discussed how we can solve this problem using DFS. In this example, Let’s solve this problem using BFS (Breadth-First Search).

To solve this problem, Traverse a 2D grid, and when we find the grid whose value is 1. Then check all connected 1’s and mark them as visited. We can only move in four directions. Also, Once all connected 1’s are traversed then increment the value of count. This process is repeated until the matrix is traversed completely.

The time complexity of this approach is O(n*m) where n is the no of rows and m is the no. of columns.

Number of islands using BFS video tutorial

Programming questions on binary tree

Tagged , , . Bookmark the permalink.

About WebRewrite

I am technology lover who loves to keep updated with latest technology. My interest field is Web Development.