Tutorialspoint
Problem
Solution
Submissions

Number of Islands in a 2D Grid

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

Write a C# program to implement the numberOfIslands(char[][] grid) function, which counts 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 surrounded by water.

Example 1
  • 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 has 3 islands.
    • The first island is formed by the first two rows, first two columns.
    • The second island is formed by the single '1' in the third row, third column.
    • The third island is formed by the two '1's in the fourth row, fourth and fifth columns.
Example 2
  • 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 formed by all the '1's that are connected horizontally or vertically.
Constraints
  • 1 ≤ grid.length, grid[i].length ≤ 300
  • grid[i][j] is either '0' or '1'
  • Time Complexity: O(m * n) where m is the number of rows and n is the number of columns
  • Space Complexity: O(m * n)
ArraysAlgorithmsPwCTutorix
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
  • When you find a '1', increment the count and perform DFS/BFS to mark all connected '1's as visited
  • Remember to only move in four directions: up, down, left, and right
  • Be careful with the grid boundaries to avoid index out of range errors

Steps to solve by this approach:

 Step 1: Check if the grid is valid. If it's null or empty, return 0.
 Step 2: Initialize a counter for the number of islands.
 Step 3: Iterate through each cell in the grid.
 Step 4: When we find a '1', increment the island counter.
 Step 5: Use DFS to mark all connected '1's as visited (by changing them to '0').
 Step 6: Continue iterating through the grid until all cells have been checked.
 Step 7: Return the final count of islands.

Submitted Code :