Tutorialspoint
Problem
Solution
Submissions

Number of Islands in a 2D Grid

Certification: Intermediate Level Accuracy: 0% Submissions: 0 Points: 15

Write a Python program to find the number of islands in a 2D grid. 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 all surrounded by water.

Algorithm for numIslands(grid)
  1. Iterate through each cell in the grid.
  2. When a land cell ('1') is found, increment the island count.
  3. Use Depth-First Search (DFS) or Breadth-First Search (BFS) to mark all connected land cells as visited.
  4. Continue until all cells are processed.
  5. Return the total count of islands found.
Example 1
  • Input: grid = [
     ["1","1","1","1","0"],
     ["1","1","0","1","0"],
     ["1","1","0","0","0"],
     ["0","0","0","0","0"] ]
  • Output: 1
  • Explanation:
    • There is only one island in the grid.
Example 2
  • Input: grid = [
     ["1","1","0","0","0"],
     ["1","1","0","0","0"],
     ["0","0","1","0","0"],
     ["0","0","0","1","1"] ]
  • Output: 3
  • Explanation:
    • There are three islands in the grid.
Constraints
  • m == grid.length
  • n == grid[i].length
  • 1 ≤ m, n ≤ 300
  • grid[i][j] is '0' or '1'.
  • Time Complexity: O(m * n)
  • Space Complexity: O(m * n)
ArraysAlgorithmsTCS (Tata Consultancy Services)HCL Technologies
Editorial

Login to view the detailed solution and explanation for this problem.

My Submissions
All Solutions
Lang Status Date Code
You do not have any submissions for this problem.
User Lang Status Date Code
No submissions found.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

Solution Hints

  • Use Depth-First Search (DFS) or Breadth-First Search (BFS) to traverse the grid.
  • Mark visited cells to avoid counting the same island multiple times.
  • For each land cell ('1'), perform a traversal to find the entire island.
  • Increment the island count for each new island discovered.
  • Consider using a visited matrix or modifying the input grid to mark visited cells.

Steps to solve by this approach:

 Step 1: Iterate through each cell in the grid
 Step 2: When we find a land cell ('1'), increment island count
 Step 3: Use DFS to mark all connected land cells as visited
 Step 4: Continue until all cells are processed
 Step 5: Return the total count of islands found

Submitted Code :