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.
CARVIEW |
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 and0
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 of1
s 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.
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
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<=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.
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:
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.
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 griddef findIslands(self, grid_input):# If the grid is empty, return 0 as there are no islandsif not grid_input:return 0count_islands = 0 # Initialize a counter for the number of islandsrows = len(grid_input) # Get the number of rows in the gridcols = len(grid_input[0]) # Get the number of columns in the gridrow = 0 # Start from the first row# Traverse through each cell of the gridwhile row < rows:col = 0 # Start from the first column in each rowwhile 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 visitedself.graphdfs(grid_input, row, col)count_islands += 1 # Increment the island count after DFScol += 1 # Move to the next columnrow += 1 # Move to the next rowreturn count_islands # Return the total number of islands found# This function performs Depth-First Search (DFS) to explore connected land cellsdef graphdfs(self, grid, row, col):# Base case: If the cell is out of bounds or not land ('1'), returnif (row < 0or col < 0or 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) recursivelyself.graphdfs(grid, row + 1, col) # Downself.graphdfs(grid, row - 1, col) # Upself.graphdfs(grid, row, col + 1) # Rightself.graphdfs(grid, row, col - 1) # Left# Helper function to print the grid like a matrixdef printGrid(self, grid):for row in grid:print(" ".join(row))# Example grid inputgrid_input = [["1", "1", "0", "0"],["1", "1", "0", "0"],["0", "0", "0", "0"],["0", "0", "0", "1"],]# Creating an instance of numIslands classsolution = numIslands()# Print the grid in matrix form before calling the functionprint("Initial Grid:")solution.printGrid(grid_input)# Calling the function with the grid inputnum_islands = solution.findIslands(grid_input)# Print the grid in matrix form after islands are markedprint("\nGrid after marking visited islands:")solution.printGrid(grid_input)# Output the resultprint("\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
andgraphdfs
.The
findIslands
method takes a 2D listgrid_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 variablecount_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
Space complexity
The overall space complexity of this code is
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:
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.
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.
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?
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.
Relevant Answers
Explore Courses
Free Resources