
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)
- Iterate through each cell in the grid.
- When a land cell ('1') is found, increment the island count.
- Use Depth-First Search (DFS) or Breadth-First Search (BFS) to mark all connected land cells as visited.
- Continue until all cells are processed.
- 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)
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 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.