Oil Deposits UVA - 572

https://vjudge.net/problem/UVA-572

图的联通块问题,遍历整个图,对每个元素用DFS深搜,并将整个联通块写入相同的编号。(又叫种子填充floodfill)

#include<iostream>
#include<vector>
#include<string>
using namespace std;
#define rep(i,n,t) for(int i=(n);i<(t);i++)
#define maxm 150
#define maxn 150
int Book[maxn][maxm]; int n, m;
vector<string> V;

void dfs(int x, int y,int count)
{
    Book[x][y] = count;
    rep(i, -1, 2) rep(j, -1, 2)
    {
        int xx = x + i; int yy = y + j;
        if (i == 0 && j == 0) continue;
        else if (xx < 0 || xx >= n || yy < 0 || yy >= m) continue;
        else if (!Book[xx][yy]&&V[xx][yy]=='@') dfs(xx, yy, count);
    }
}




int main()
{
    int cnt=0;
    cin >> n >> m;
    while (n&&m)
    {    
        memset(Book, 0, sizeof(Book));
        V.clear();
        rep(i, 0, n)
        {
            string temp;
            cin >> temp;
            V.push_back(temp);
        }
        rep(i, 0, n) rep(j, 0, m)
        {
            if (!Book[i][j]&&V[i][j]=='@') dfs(i,j,++cnt);
        }
        cout << cnt<<endl; cnt = 0;
        cin >> n >> m;
    }
    return 0;
}

 

posted @ 2019-03-15 20:12  超融合  阅读(198)  评论(0编辑  收藏  举报