200. Number of Islands
Medium
Description
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 all 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
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
Constraints:
m == grid.length
n == grid[i].length
1 <= m, n <= 300
grid[i][j]
is '0' or '1'.
Solutions π
Approach: BFS on Grid/Maze/2D Matrix
Time complexity: \(O(mn)\), where \(m\) is the number of rows and \(n\) is the number of columns in the grid.
Space complexity: \(O(min(m,n))\)
When Input modification is not allowed
Modify
Replace the following in above BFS algorithm, when you can modify input
Quick tip
-
Don't go for DFS Stick to BFS
-
Interviewers do not want you to modify the input array
-
Stick to BFS for interviews
Approach: DFS on Grid/Maze/2D Matrix
Time complexity: \(O(mn)\)
Space complexity: \(O(mn)\)
When input modification is allowed
Algorithm
To solve this problem, we'll use a depth-first search (DFS).
We'll iterate through each cell in the grid.
When we find a '1', we'll mark it as visited and explore all adjacent land cells using DFS. This process counts as one island. We'll do this for all cells in the grid.
The time complexity of this solution is \(O(m \cdot n)\), where m is the number of rows and n is the number of columns in the grid. Thatβs because we visit each cell once.