# 200. Number of Islands
Given a 2d grid map of '1's (land) and '0's (water), count 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:
11110
11010
11000
00000
Output: 1
Example 2:
Input:
11000
11000
00100
00011
Output: 3
# Solution
Approach 1: DFS.
Approach 1: BFS
Approach 2: Union find.
# Code (Python)
Approach 1:
class Solution:
def numIslands(self, grid: List[List[str]]) -> int:
def mark_island(r, c):
grid[r][c] = '-1'
for x, y in ((0, 1), (0, -1), (1, 0), (-1, 0)):
if 0 <= r + x < len(grid) and 0 <= c + y < len(grid[0]):
if grid[r + x][c + y] == '1':
mark_island(r + x, c + y)
num_islands = 0
for r in range(len(grid)):
for c in range(len(grid[0])):
if grid[r][c] == '1':
num_islands += 1
mark_island(r, c)
return num_islands
# Code (C++)
Approach 1:
// DFS.
class Solution {
private:
void markIsland(vector<vector<char>>& grid, int y, int x) {
if (grid[y][x] != '1')
return;
grid[y][x] = '2';
if (y > 0)
markIsland(grid, y - 1, x);
if (y < grid.size() - 1)
markIsland(grid, y + 1, x);
if (x > 0)
markIsland(grid, y, x - 1);
if (x < grid[0].size() - 1)
markIsland(grid, y, x + 1);
}
public:
int numIslands(vector<vector<char>>& grid) {
int m = grid.size();
if (m == 0) return 0;
int n = grid[0].size();
if (n == 0) return 0;
int count = 0;
for (int i = 0; i < m; ++i)
{
for (int j = 0; j < n; ++j)
{
if (grid[i][j] == '1')
{
count++;
markIsland(grid, i, j);
}
}
}
return count;
}
};