Practice Problem
Number of Islands
Difficulty: Medium
Given a 2D grid of '1's (land) and '0's (water), count the number of distinct islands formed by connected land cells.
Number of Islands
Given an m x n 2D binary grid grid which represents a map of '1's (land) and '0's (water), return the number of islands.
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.
Examples
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: All the 1s in the top-left are connected,
forming a single island.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 separate groups of connected 1s.Example 3:
Input: grid = [["0","0"],["0","0"]]
Output: 0
Explanation: No land cells, so zero islands.Constraints
m == grid.lengthn == grid[i].length1 <= m, n <= 300grid[i][j]is'0'or'1'
Expected Complexity
- Time: O(m * n)
- Space: O(m * n) in the worst case for the recursion stack or BFS queue
MEDIUM
Graphs
DFS
BFS
Islands / Flood Fill
Intermediate
0 views
Solution
Hints
Hint 1
Hint 2
Premium
Hint 3
Premium
Hint 4
Premium
This section is available for CodeSnatch Premium members only.
