Tutorialspoint
Problem
Solution
Submissions

Number of Islands

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

Write a C program to count the number of islands in a 2D binary 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 surrounded by water.

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: The grid contains connected '1's that form a single island. All '1's are connected either horizontally or vertically. Therefore, there is 1 island in total.
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: The grid contains three separate groups of connected '1's. First island: top-left 2x2 block of '1's. Second island: single '1' at position (2,2). Third island: two connected '1's at bottom-right. Therefore, there are 3 islands in total.
Constraints
  • 1 ≤ grid.length ≤ 300
  • 1 ≤ grid[i].length ≤ 300
  • grid[i][j] is '0' or '1'
  • Time Complexity: O(m*n) where m and n are grid dimensions
  • Space Complexity: O(m*n) in worst case for recursion stack
ArraysAlgorithmsDeloitteAirbnb
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) to traverse connected components.
  • Iterate through each cell in the grid.
  • When you find a '1', increment island count and start DFS.
  • In DFS, mark current cell as visited by changing '1' to '0'.
  • Recursively visit all adjacent cells (up, down, left, right).
  • Continue until all connected '1's are visited and marked.

Steps to solve by this approach:

 Step 1: Initialize island counter to 0 and get grid dimensions.

 Step 2: Iterate through each cell in the 2D grid using nested loops.
 Step 3: When a cell contains '1', increment the island counter.
 Step 4: Call DFS function to mark all connected '1's as visited.
 Step 5: In DFS, check boundary conditions and if current cell is '1'.
 Step 6: Mark current cell as '0' to indicate it's been visited.
 Step 7: Recursively call DFS on all 4 adjacent cells (up, down, left, right).

Submitted Code :