
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.
- The grid contains connected land cells marked as "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.
- The grid contains three separate groups of connected land cells.
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
Editorial
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. | ||||
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