解题思路:
(1)dfs
class Solution {
private:
vector<vector<int>> d={{1,0},{-1,0},{0,1},{0,-1}};
int m,n;
public:
void helper(vector<vector<int>> &v,vector<vector<char> >& grid,int x,int y) {
v[x][y]=1;
for(int i=0;i<d.size();i++) {
int x1=x+d[i][0];
int y1=y+d[i][1];
if(0<=x1 && x1<m && 0<=y1 && y1<n && grid[x1][y1]=='1' && v[x1][y1]==0)
helper(v,grid,x1,y1);
}
return;
}
int solve(vector<vector<char> >& grid) {
int count=0;
m=grid.size();
n=grid[0].size();
vector<vector<int>> v(m,vector<int>(n,0));
for(int i=0;i<m;i++) {
for(int j=0;j<n;j++) {
if(grid[i][j]=='1' && v[i][j]==0) {
count++;
helper(v,grid,i,j);
}
}
}
return count;
}
};