Problem: 200. 岛屿数量
文章目录
- 题目描述
- 思路及解法
- 复杂度
- Code
题目描述
思路及解法
1.遍历矩阵grid的每一个位置;若某个位置为’1’则将用于记录岛屿数量的变量count++,并调用dfs函数;
2.dfs函数实现:2.1.若当前grid位置为’0’则直接返回;若超出了grid的边界也直接返回;
2.2.若当前位置为’1’则将其变为海水即覆盖为’0’,并向其上下左右方向DFS
复杂度
时间复杂度:
O ( M × N ) O(M \times N) O(M×N);其中 M M M和 N N N分别为举证grid的行数与列数
空间复杂度:
O ( M × N ) O(M \times N) O(M×N)
Code
class Solution {
public:
/**
* Use DFS to get the maximum number of islands
*
* @param grid Island array
* @return int
*/
int numIslands(vector<vector<char>>& grid) {
int count = 0;
int m = grid.size();
int n = grid[0].size();
for (int i = 0; i < m; ++i) {
for (int j = 0; j < n; ++j) {
if (grid[i][j] == '1') {
count++;
dfs(grid, i, j);
}
}
}
return count;
}
/**
* DFS implementation function
*
* @param grid Island array
* @param i Index subscript
* @param j Index subscript
*/
void dfs(vector<vector<char>>& grid, int i, int j) {
int m = grid.size();
int n = grid[0].size();
// out of index
if (i < 0 || j < 0 || i >= m || j >= n) {
return;
}
// It's already sea water
if (grid[i][j] == '0') {
return;
}
// Turn grid[i][j] into seawater
grid[i][j] = '0';
// Flood the land up and down
dfs(grid, i + 1, j);
dfs(grid, i, j + 1);
dfs(grid, i - 1, j);
dfs(grid, i, j - 1);
}
};