题意:给一个01矩阵,求1的连通块有多少块。
题解:dfs所有没被遍历过的1.
class Solution {
public:
int dir[4][2] = {{1,0},{-1,0},{0,-1},{0,1}};
void dfs(int x,int y,vector<vector<char>>& grid,vector<vector<bool>>& vis)
{
vis[x][y] = true;
int n = grid.size();
int m = grid[0].size();
for(int i = 0; i < 4; i++)
{
int tx = x + dir[i][0];
int ty = y + dir[i][1];
if(tx < 0 || ty < 0 || tx >= n || ty >= m || vis[tx][ty] || grid[tx][ty] == '0') continue;
dfs(tx,ty,grid,vis);
}
}
int numIslands(vector<vector<char>>& grid) {
int n = grid.size();
if(n == 0) return 0;
int m = grid[0].size();
vector<bool> ini;
vector<vector<bool>> vis;
for(int i = 0; i <= m; i++) ini.push_back(false);
for(int i = 0; i <= n; i++) vis.push_back(ini);
int ans = 0;
for(int i = 0; i < n; i++)
{
for(int j = 0; j < m; j++)
{
if(grid[i][j] == '1' && !vis[i][j])
{
dfs(i,j,grid,vis);
ans++;
}
}
}
return ans;
}
};