# 200 Number of Islands

## 1. Question

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:
11110
11010
11000
00000
Example 2:
11000
11000
00100
00011

## 2. Implementation

(1) BFS
class Solution {
public int numIslands(char[][] grid) {
if (grid == null || grid.length == 0) {
return 0;
}
int[][] directions = {{0, -1}, {0, 1}, {-1, 0}, {1, 0}};
int m = grid.length, n = grid.length;
int count = 0;
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (grid[i][j] == '1') {
++count;
searchByBFS(grid, i, j, m, n, directions);
}
}
}
return count;
}
public void searchByBFS(char[][] grid, int row, int col, int m, int n, int[][] directions) {
grid[row][col] = '0';
while (!queue.isEmpty()) {
int curPoint = queue.remove();
int curRow = curPoint / n;
int curCol = curPoint % n;
for (int[] direction : directions) {
int nextRow = curRow + direction;
int nextCol = curCol + direction;
if (isValid(grid, nextRow, nextCol)) {
grid[nextRow][nextCol] = '0';
}
}
}
}
public boolean isValid(char[][] grid, int row, int col) {
return row >= 0 && row < grid.length && col >= 0 && col < grid.length && grid[row][col] == '1';
}
}
(2) DFS
class Solution {
public int numIslands(char[][] grid) {
if (grid == null || grid.length == 0 || grid.length == 0) {
return 0;
}
int m = grid.length, n = grid.length;
int count = 0;
int[][] directions = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (grid[i][j] == '1') {
++count;
searchIslandByDFS(i, j, grid, directions);
}
}
}
return count;
}
public void searchIslandByDFS(int row, int col, char[][] grid, int[][] directions) {
grid[row][col] = '0';
for (int[] direction : directions) {
int nextRow = row + direction;
int nextCol = col + direction;
if (isValid(nextRow, nextCol, grid)) {
searchIslandByDFS(nextRow, nextCol, grid, directions);
}
}
}
public boolean isValid(int row, int col, char[][] grid) {
return row >= 0 && row < grid.length && col >= 0 && col < grid.length && grid[row][col] == '1';
}
}

## 3. Time & Space Complexity

BFS: 时间复杂度O(mn), 空间复杂度:O(mn)
DFS: 时间复杂度O(mn), 空间复杂度:O(mn)