05-1. List Components (25)图的基本遍历

05-1. List Components (25)

时间限制 200 ms

内存限制 65536 kB

代码长度限制 8000 B

判题程序
Standard 作者 CHEN, Yue

For a given undirected graph with N vertices and E edges, please list all the connected components by both DFS and BFS. Assume that all the vertices are numbered from 0 to N-1. While searching, assume that we always start from the vertex with the smallest index, and visit its adjacent vertices in ascending order of their indices.

Input Specification:

Each input file contains one test case. For each case, the first line gives two integers N (0<N<=10) and E, which are the number of vertices and the number of edges, respectively. Then E lines follow, each described an edge by giving the two ends. All the numbers in a line are separated by a space.

Output Specification:

For each test case, print in each line a connected component in the format “{ v1 v2 … vk }”. First print the result obtained by DFS, then by BFS.

Sample Input:

8 6
0 7
0 1
2 0
4 1
2 4
3 5

Sample Output:

{ 0 1 4 2 7 }
{ 3 5 }
{ 6 }
{ 0 1 2 7 4 }
{ 3 5 }
{ 6 }

提交代

#include <iostream>
#include <algorithm>
#include <string>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <cmath>
#include <vector>
#include<queue>
#include<stack>
#include<map>
#include<set>
using namespace std;
#define lson rt<<1,l,MID
#define rson rt<<1|1,MID+1,r
//#define lson root<<1
//#define rson root<<1|1
#define MID ((l+r)>>1)
typedef long long ll;
typedef pair<int,int> P;
const int maxn=100;
const int base=1000;
const int inf=999999;
const double eps=1e-5;
vector<int> G[maxn];
int n;
bool vist[maxn];//dfs񈬀
bool vis[maxn];//bfs񈬀
void dfs(int s)
{
    if(!vist[s])
    {
        vist[s]=true;
        printf("%d ",s);
        sort(G[s].begin(),G[s].end());
        for(int i=0; i<G[s].size(); i++)
        {
            if(!vist[G[s][i]])dfs(G[s][i]);
        }
    }
}


void bfs(int s)
{
    queue<int> q;
    q.push(s);
    while(!q.empty())
    {
        int k=q.front();
        q.pop();
        if(!vis[k])
        {
            vis[k]=true;
            printf("%d ",k);
        }
        else
            continue;
        sort(G[k].begin(),G[k].end());
        for(int i=0; i<G[k].size(); i++)
            q.push(G[k][i]);


    }
}
int main()
{
    int m,i,j,k,t;
    cin>>n>>m;
    while(m--)
    {
        int s,e;
        cin>>s>>e;
        G[s].push_back(e);
        G[e].push_back(s);
    }
    for(i=0; i<n; i++)
    {


        if(!vist[i])
        {
            printf("{ ");
            dfs(i);
            printf("}\n");
        }


    }
   // printf("------------------\n");
    for(i=0; i<n; i++)
    {
        if(!vis[i])
        {
            printf("{ ");
            bfs(i);
            printf("}\n");
        }
    }
    return 0;
}











    原文作者:数据结构之图
    原文地址: https://blog.csdn.net/u013167299/article/details/42245459
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞