
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)
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
- 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