200. Number of Islands
1. 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.
2. Example
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
3. Constraints
- m == grid.length
- n == grid[i].length
- 1 <= m, n <= 300
- grid[i][j] is ‘0’ or ‘1’.
4. Solutions
Breadth-First Search
n is the number of letters in grid
Time complexity: O(n)
Space complexity: O(n)
class Solution {
public:
int numIslands(const vector<vector<char>> &grid) {
auto worker_grid(grid);
for (int i = 0; i < worker_grid.size(); ++i) {
for (int j = 0; j < worker_grid[0].size(); ++j) {
if (worker_grid[i][j] == '1') {
++_island_count;
traverse(worker_grid, i, j);
}
}
}
return _island_count;
}
private:
int _island_count = 0;
void traverse(vector<vector<char>> &worker_grid, int row, int column) {
if (0 <= row && row < worker_grid.size() && 0 <= column && column < worker_grid[0].size() &&
worker_grid[row][column] == '1') {
worker_grid[row][column] = '0';
traverse(worker_grid, row + 1, column);
traverse(worker_grid, row - 1, column);
traverse(worker_grid, row, column + 1);
traverse(worker_grid, row, column - 1);
}
}
};