Tutorialspoint
Problem
Solution
Submissions

Number of Islands

Certification: Intermediate Level Accuracy: 100% Submissions: 1 Points: 10

Write a JavaScript 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 land cells marked as "1".
    • All the "1" cells are connected either horizontally or vertically.
    • Since all land cells form one connected component, there is only 1 island.
    • Therefore, the answer is 1.
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 land cells.
    • The first island is formed by the top-left 2x2 block of "1"s.
    • The second island is the single "1" in the middle of the grid.
    • The third island is formed by the bottom-right 1x2 block of "1"s.
    • Therefore, the answer is 3.
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) in worst case for recursion stack
ArraysAlgorithmsFacebookEY
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 explore connected components
  • Iterate through each cell in the grid
  • When you find a land cell ('1'), increment the island count and start DFS/BFS
  • Mark all connected land cells as visited to avoid counting them again
  • Continue until all cells have been processed

Steps to solve by this approach:

 Step 1: Initialize variables for grid dimensions and island counter.
 Step 2: Create a DFS helper function to explore connected land cells.
 Step 3: In DFS, check boundaries and water cells, then mark current cell as visited.
 Step 4: Recursively explore all four adjacent directions (up, down, left, right).
 Step 5: Iterate through each cell in the grid using nested loops.
 Step 6: When a land cell is found, increment island count and start DFS exploration.
 Step 7: Return the total count of islands found.

Submitted Code :