FIG connectivity problems -BFS

Graph theory there is a fundamental problem, and that is not a problem to determine the connectivity map, today we have to discuss this issue, we know that a picture can have two representations in the computer, one adjacency matrix two is adjacent to the table, where the adjacency matrix representation, we have introduced the minimum spanning tree problem discussed, today we have to discuss connectivity issues represented by the adjacency list graph in the classroom. Requirements solved by BFS method.

Input

本问题有多组测试数据,每组测试数据有两部分,第一部分只有一行,是两个正整数,分别表示图的节点数N(节点
编号从1到N,1<=N<=100)和图的边数E;第二部分共有E行,每行也是两个整数N1,N2(1<=N1,N2<=N),分
别表示N1和N2之间有一条边。

Output

对于每一组测试数据,输出只有一行,如果是连通图,那么输出“Yes”,否则输出“No”。

Sample Input

6 10
1 2
1 3
1 4
1 5
1 6
2 3
2 4
3 4
3 5
3 6
4 3
1 2
1 3
2 3

Sample Output

Yes
No
#include<bits/stdc++.h>
using namespace std;
const int MAXN=100005;
int g[MAXN],tot,n,m,u,v;
bool vis[MAXN];
struct edge
{
    int to,next;
}e[MAXN];
void add_edge(int from,int to)
{
    e[++tot].to=to;
    e[tot].next=g[from];
    g[from]=tot;
}
void bfs(int x)
{
    vis[x]=true;
    queue<int>q;
    q.push(x);
    while(!q.empty())
    {
        int now=q.front();
        q.pop();
        for(int i=g[now];i;i=e[i].next)
        {
            if(!vis[e[i].to])
            {
                vis[e[i].to]=true;
                q.push(e[i].to);
            }
        }
    }
    return;
}
int main()
{
    while(scanf("%d %d",&n,&m)!=EOF)
    {
        tot=0;
        for(int i=1;i<=n;++i)
        {
            g[i]=0;
            vis[i]=false;
        }
        for(int i=1;i<=m;++i)
        {
            scanf("%d %d",&u,&v);
            add_edge(u,v);
            add_edge(v,u);
        }
        bfs(1);
        bool f=true;
        for(int i=1;i<=n;++i)
        {
            if(!vis[i])
            {
                f=false;
            }
        }
        printf("%s\n",f?"Yes":"No");
    }
    return 0;
}
#include<bits/stdc++.h>
using namespace std;
const int MAXN=100005;
int n,m,u,v;
bool vis[MAXN];
vector<int>G[MAXN];
void bfs(int x)
{
    vis[x]=true;
    queue<int>q;
    q.push(x);
    while(!q.empty())
    {
        int now=q.front();
        q.pop();
        for(auto &i:G[now])
        {
            if(!vis[i])
            {
                vis[i]=true;
                q.push(i);
            }
        }
    }
    return;
}
int main()
{
    while(scanf("%d %d",&n,&m)!=EOF)
    {
        for(int i=1;i<=n;++i)
        {
            G[i].clear();
            vis[i]=false;
        }
        for(int i=1;i<=m;++i)
        {
            scanf("%d %d",&u,&v);
            G[u].push_back(v);
            G[v].push_back(u);
        }
        bfs(1);
        bool f=true;
        for(int i=1;i<=n;++i)
        {
            if(!vis[i])
            {
                f=false;
            }
        }
        printf("%s\n",f?"Yes":"No");
    }
    return 0;
}

Guess you like

Origin blog.csdn.net/weixin_44061561/article/details/94449126