Number of Islands LeetCode

In computer science, the LeetCode Number of Islands problem tests a programmer’s ability to solve graph problems. The problem can be applied in real-world scenarios such as image processing, where it can be used to identify objects in an image. In this problem, our goal is to identify islands within a grid of 1s and 0s. By solving this puzzle, we learn to navigate grids and understand connections, making it an engaging journey of discovery.

Key takeaways:

  • Problem understanding: The problem involves a 2D grid where 1 represents land and 0 represents water. Islands are formed by connecting adjacent lands (horizontally or vertically). The goal is to count the number of distinct islands in the grid.

  • Approach: Depth-First Search (DFS) is used to explore and traverse the grid. For each land cell (1), the DFS explores all connected land cells, marking them as visited to avoid revisiting the same island. The DFS traversal ensures that each connected group of 1s is counted as one island.

  • Real-world application: This problem can be applied to image processing, where detecting connected components (like objects in an image) is analogous to identifying islands in the grid.

Let’s consider the following illustration to see islands formation within a grid.

A high-level glimpse of the LeetCode Number of Islands problem
A high-level glimpse of the LeetCode Number of Islands problem

The illustration above sets the groundwork for the problem that we will explore in more detail within the problem statement.

Problem statement

Consider a 2D grid of size (m×n).(m \times n ). Each cell in the grid consists of either 1 or 0. The value of 1 represents land, and a value of 0 represents water. Connecting adjacent 1s horizontally or vertically (not diagonally) forms islands. Our task is to identify the number of islands that exist on the grid.

Some important points that need to be remembered while solving this problem:

  • Each cell of the grid either consists of 1s or 0s.

  • Diagonal connections within an island are not considered.

  • Every row within the grid should be of the same size.

  • The grid should contain a minimum of 1 and a maximum of 300 rows and columns, e.g., 1<=m,n<=3001 <= m, n <= 300.

The LeetCode Number of Islands problem involves determining the number of islands surrounded by the water under these constraints. The result should be an integer representing the number of islands. Now, let's map our previous example to the problem for better understanding.

We explore the left grid from the top-left corner and we encounter a 0 representing water, we color it blue in the right grid.
1 of 22

In the slides above, we discuss how we can explore the whole grid to find the number of islands. Let's quickly test our understanding of this problem.

Knowledge test

Now that we have understood the problem, let’s check our knowledge by finding the number of islands for the examples below:

Knowledge test
Knowledge test

Note: If you’re stuck, click the “Show Solution” button.

Solution to Number of Islands problem

Now that we’ve understood the problem, let’s understand it programmatically. To traverse the whole grid, we use depth-first search (DFS). Let's discuss how we employ DFS to traverse the whole grid to find number of islands:

  • If the grid is empty, return 0 (no islands).

  • Initialize count to 0 (to count the number of islands).

  • Iterate through each cell in the grid using nested loops.

  • If the current cell is 1, initiate a DFS (graphdfs(self, grid, row, col)) and increment the count:

    • If the current cell is out of grid boundaries or not part of the island, return without further exploration (base case).

    • Mark the current cell as visited by changing “1” to “#.”

    • Recursively call DFS on adjacent cells (up, down, left, right) to explore the island:

      • Move down: graphdfs(grid, row+1, col)

      • Move up: graphdfs(grid, row-1, col)

      • Move right: dfgraphdfs(grid, row, col+1)

      • Move left: graphdfs(grid, row, col-1)

  • After exploring all islands using DFS, return the total number of islands in the grid.

Number of Islands LeetCode
1 of 18

In the slides above, we found one island as we performed the first iteration only. We need to check each cell in the grid marked as 1. When it finds a 1, it begins exploring (through DFS) that area to find the whole island connected to it. After completing this exploration, it moves on to the next 1 in the grid to search for another island. This process repeats until it has checked every 1 cell, ensuring it finds and counts all the islands present in the whole grid.

Code for implementing Number of Islands solution

Let’s have a look at the code for the algorithm we just discussed:

class numIslands(object):
# This function finds the number of islands in the given grid
def findIslands(self, grid_input):
# If the grid is empty, return 0 as there are no islands
if not grid_input:
return 0
count_islands = 0 # Initialize a counter for the number of islands
rows = len(grid_input) # Get the number of rows in the grid
cols = len(grid_input[0]) # Get the number of columns in the grid
row = 0 # Start from the first row
# Traverse through each cell of the grid
while row < rows:
col = 0 # Start from the first column in each row
while col < cols:
# If the current cell contains '1' (part of an island)
if grid_input[row][col] == "1":
# Perform DFS to mark all connected land ('1') as visited
self.graphdfs(grid_input, row, col)
count_islands += 1 # Increment the island count after DFS
col += 1 # Move to the next column
row += 1 # Move to the next row
return count_islands # Return the total number of islands found
# This function performs Depth-First Search (DFS) to explore connected land cells
def graphdfs(self, grid, row, col):
# Base case: If the cell is out of bounds or not land ('1'), return
if (
row < 0
or col < 0
or row >= len(grid)
or col >= len(grid[0])
or grid[row][col] != "1"
):
return
# Mark the current cell as visited by setting it to '#'
grid[row][col] = "#"
# Explore all four directions (down, up, right, left) recursively
self.graphdfs(grid, row + 1, col) # Down
self.graphdfs(grid, row - 1, col) # Up
self.graphdfs(grid, row, col + 1) # Right
self.graphdfs(grid, row, col - 1) # Left
# Helper function to print the grid like a matrix
def printGrid(self, grid):
for row in grid:
print(" ".join(row))
# Example grid input
grid_input = [
["1", "1", "0", "0"],
["1", "1", "0", "0"],
["0", "0", "0", "0"],
["0", "0", "0", "1"],
]
# Creating an instance of numIslands class
solution = numIslands()
# Print the grid in matrix form before calling the function
print("Initial Grid:")
solution.printGrid(grid_input)
# Calling the function with the grid input
num_islands = solution.findIslands(grid_input)
# Print the grid in matrix form after islands are marked
print("\nGrid after marking visited islands:")
solution.printGrid(grid_input)
# Output the result
print("\nNumber of islands:", num_islands)

Code explanation

Here’s the explanation of the code:

  • Line 1: The numIslands class is defined with two methods: findIslands and graphdfs.

    • The findIslands method takes a 2D list grid_input as input and returns the number of islands in the grid.

    • The graphdfs method is a helper method that performs depth-first search (DFS) on the grid to find the islands.

  • Lines 3–6: The function first checks if the input grid is empty. If it is empty, the function returns 0.

  • Line 8: The findIslands method initializes a counter variable count_islands to 0 and iterates over each cell in the grid.

  • Lines 15–25: If the cell value is 1, it means that a new island has been found. The graphdfs method is called to mark all the cells in the island as visited.

  • Line 22: The count_islands variable is incremented by 1 for each new island found.

  • Line 25: Finally, the findIslands method returns the total number of islands found in the grid.

Time complexity

The time complexity of this code is O(m×n)O(m \times n) where mm is the number of rows in the grid, andnnis the number of columns. This complexity arises due to the nested loops that iterate through each cell in the grid once.

Space complexity

The overall space complexity of this code is O(m×n)O(m × n) due to the input matrix and the recursion stack during DFS, which means it depends on the maximum depth of recursion.

Coding problems similar to Number of Islands

There are several other coding problems that involve similar concepts of exploring grids, identifying connected components, and solving graph traversal challenges, providing excellent practice for sharpening your skills in this area. Here are a few problems that are similar to the Number of Islands problem:

  1. Flood Fill: Given a grid, starting from a pixel, the goal is to change all connected pixels of the same color to a new color. This problem uses similar DFS/BFS techniques.

  2. Pacific Atlantic Water Flow: You are given a grid where water can flow to either the Pacific or Atlantic ocean. The goal is to determine which cells can flow water to both oceans.

  3. Max Area of Island: This problem requires finding the largest island in a 2D grid. By exploring connected land cells (1s) using DFS or BFS, the task is to calculate the maximum area of any island present in the grid.

On that note, take a look at some other Answers that cover solutions to frequently asked LeetCode problems in detail:

If you think you're done preparing for the technical interview, try attempting Educative's AI-empowered mock interviews. Mock interviews, in general, help you build confidence, improve your problem-solving skills, and identify areas where you can improve before the actual interview. To make it even more helpful for you, Educative's AI-empowered mock interviewer gives an unbiased evaluation.

Frequently asked questions

Haven’t found what you were looking for? Contact Us


Is Number of Islands a graph problem?

Yes, the Number of Islands problem is a graph problem because it involves identifying connected components within a grid. The grid can be viewed as a graph where each cell is a node, and an edge exists between two nodes if they are adjacent horizontally or vertically and represent land (1). The goal is to count the number of distinct connected components (islands) using graph traversal algorithms like Depth-First Search (DFS) or Breadth-First Search (BFS). These algorithms explore each island by visiting all connected land cells and marking them as visited to avoid double counting, making it a classic graph traversal challenge.


What is the difference between counting islands and counting connected components in a graph?

Counting islands in a grid is equivalent to counting connected components in a graph. In this problem, each land cell (1) is a node, and connections are made horizontally or vertically (not diagonally). DFS (or BFS) is used to find all connected nodes (lands) to count them as a single island.


Why can't we count diagonally connected land cells as part of an island?

The problem specifies that only horizontal and vertical connections count towards an island. Diagonal connections are not considered part of the same island, which simplifies the problem and ensures a clear definition of adjacency.


Can this problem be solved using Breadth-First Search (BFS) instead of DFS?

Yes, BFS can also be used to solve this problem. Instead of using recursion (as in DFS), BFS uses a queue to explore neighboring cells in a level-by-level manner. The time complexity remains the same for both approaches.


Free Resources

Copyright ©2024 Educative, Inc. All rights reserved