HDOJ1232 畅通工程 DFS

很早之前就做过的题以前用并查集做的

现在用DFS重做算是熟悉DFS吧

#include<stdio.h>
#include<string.h>
const int size=1000;
int graph[size][size];
int visit[size];
int cout;
int n,m;
void get_graph()
{
    memset(graph,0,sizeof(graph));
    memset(visit,0,sizeof(visit));
    int t1,t2;
    for(int i=0;i<m;i++)
    {
        scanf("%d%d",&t1,&t2);
        graph[t1][t2]=1;
        graph[t2][t1]=1;
    }
}
void dfs(int a)
{
    visit[a]=1;
    for(int i=1;i<=n;i++)
        if(visit[i]==0&&graph[a][i]==1)
    {
        visit[i]=1;
        dfs(i);
    }
}
int main()
{
    //freopen("data.in","r",stdin);
    while(scanf("%d",&n)!=EOF)
    {
        if(n==0) break;
        scanf("%d",&m);
        cout=0;
        get_graph();
        for(int i=1;i<=n;i++)
        {
            if(visit[i]==0)
            {
                cout++;
                dfs(i);
            }
        }
        printf("%d\n",cout-1);
    }
    return 0;
}

posted @ 2014-01-27 11:36  ACalvin  阅读(182)  评论(0编辑  收藏  举报