题目要求
思路
1.使用广度优先遍历,将数组中所有为1的元素遍历一遍,遍历过程中使用递归,讲该元素的上下左右四个方向的元素值也置为0
2.统计一共执行过多少次,次数就是岛屿数量
代码实现
class Solution {
public:
int solve(vector<vector<char> >& grid) {
int n = grid.size();
int m = grid[0].size();
int index = 0;
for(int i = 0; i < n; i++)
{
for(int j = 0; j < m; j++)
{
if(grid[i][j] == '1')
{
index++;
// cout << i << " " << j <<endl;
dfs(grid, i, j);
}
}
}
return index;
}
void dfs(vector<vector<char>>& grid, int i, int j)
{
if(grid[i][j] == '1')
grid[i][j] = '0';
if(i > 0 && grid[i-1][j] == '1')
dfs(grid, i-1, j);
if(j > 0 && grid[i][j-1] == '1')
dfs(grid, i, j-1);
if(i < grid.size() - 1 && grid[i+1][j] == '1')
dfs(grid, i+1, j);
if(j < grid[0].size() - 1 && grid[i][j+1] == '1')
dfs(grid, i, j+1);
}
};