
Problem
Solution
Submissions
Number of Islands
Certification: Intermediate Level
Accuracy: 0%
Submissions: 0
Points: 10
Write a C 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 '1's that form a single island. All '1's are connected either horizontally or vertically. Therefore, there is 1 island in total.
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 '1's. First island: top-left 2x2 block of '1's. Second island: single '1' at position (2,2). Third island: two connected '1's at bottom-right. Therefore, there are 3 islands in total.
Constraints
- 1 ≤ grid.length ≤ 300
- 1 ≤ grid[i].length ≤ 300
- grid[i][j] is '0' or '1'
- Time Complexity: O(m*n) where m and n are grid dimensions
- 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) to traverse connected components.
- Iterate through each cell in the grid.
- When you find a '1', increment island count and start DFS.
- In DFS, mark current cell as visited by changing '1' to '0'.
- Recursively visit all adjacent cells (up, down, left, right).
- Continue until all connected '1's are visited and marked.