HDU 1269 迷宫城堡 两次dfs

为了训练小希的方向感,Gardon建立了一座大城堡,里面有N个房间(N<=10000)和M条通道(M<=100000),每个通道都是单向的,就是说若称某通道连通了A房间和B房间,只说明可以通过这个通道由A房间到达B房间,但并不说明通过它可以由B房间到达A房间。Gardon需要请你写个程序确认一下是否任意两个房间都是相互连通的,即:对于任意的i和j,至少存在一条路径可以从房间i到房间j,也存在一条路径可以从房间j到房间i。

Input

输入包含多组数据,输入的第一行有两个数:N和M,接下来的M行每行有两个数a和b,表示了一条通道可以从A房间来到B房间。文件最后以两个0结束。

Output

对于输入的每组数据,如果任意两个房间都是相互连接的,输出"Yes",否则输出"No"。

Sample Input

3 3
1 2
2 3
3 1
3 3
1 2
2 3
3 2
0 0

Sample Output

Yes
No

 判断强连通可以通过正向dfs+反向dfs判断。

如果正反都能走通,则判定为强连通。

代码如下:

#include <cstdio>
#include <cstring>
#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
const int maxn=10005;
int vis[maxn];
int n,m;
int ans;
vector <int>v1[maxn];
vector <int>v2[maxn];
void init1()
{
    for (int i=0;i<=n;i++)
    {
        v1[i].clear();
        v2[i].clear();
    }
}
void init2()
{
    ans=0;
    memset (vis,0,sizeof(vis));
}
void dfs (int loc,vector<int>*v)
{
    vis[loc]=1;
    ans++;
    for (int i=0;i<v[loc].size();i++)
    {
        int c=v[loc][i];
        if(!vis[c])
            dfs (c,v);
    }
}
int main()
{
    while (scanf("%d%d",&n,&m)!=EOF&&n||m)
    {
        init1();
        while (m--)
        {
             int x,y;
             scanf("%d%d",&x,&y);
             v1[x].push_back(y);
             v2[y].push_back(x);
        }
        init2();
        dfs(1,v1);
        if(ans==n)
        {
            init2();
            dfs(1,v2);
            printf("%s\n",ans==n?"Yes":"No");
        }
        else
            printf("No\n");
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_41410799/article/details/82316123