求助!!!
查看原帖
求助!!!
1053780
Gcx_20121118楼主2023/8/1 21:57
#include <bits/stdc++.h>
using namespace std;

int n, m, cnt = 0, dx[] = {0, 0, -1, 1}, dy[] = {1, -1, 0, 0};

bool vis[105][105], g[105][105];

void dfs(int x, int y)
{
    vis[x][y] = 1;
    for (int i = 0; i <= 3; i++)
    {
        int nx = x + dx[i], ny = y + dy[i];
        if (nx < 1 || nx > n || ny < 1|| nx > m || !g[nx][ny] || vis[nx][ny]) continue;
        dfs(nx, ny);
    }
}

int main()
{
    cin >> n >> m;
    for (int i = 1; i <= n; i++)
    {
        for (int j = 1; j <= m; j++)
        {
            char a;
            cin >> a;
            g[i][j] = (a == '0' ? 0 : 1);
        }
    }
    for (int i = 1; i <= n; i++)
    {
        for (int j = 1; j <= m; j++)
        {
            if (g[i][j] && !vis[i][j])
            {
                cnt++;
                dfs(i, j);
            }
        }
    }
    cout << cnt << "\n";
    return 0;
}
2023/8/1 21:57
加载中...