7-7 列出连通集(25 分) 【图的遍历】

7-7 列出连通集(25 分)

给定一个有N个顶点和E条边的无向图,请用DFS和BFS分别列出其所有的连通集。假设顶点从0到N−1编号。进行搜索时,假设我们总是从编号最小的顶点出发,按编号递增的顺序访问邻接点。
输入格式:

输入第1行给出2个整数N(0

#include <cstdio>
#include <cstring>
#include <ctype.h>
#include <cstdlib>
#include <cmath>
#include <climits>
#include <ctime>
#include <iostream>
#include <algorithm>
#include <deque>
#include <vector>
#include <queue>
#include <string>
#include <map>
#include <stack>
#include <set>
#include <numeric>
#include <sstream>
#include <iomanip>
#include <limits>

#define CLR(a) memset(a, 0, sizeof(a))
#define pb push_back

using namespace std;
typedef long long ll;
typedef long double ld;
typedef unsigned long long ull;
typedef pair <int, int> pii;
typedef pair <ll, ll> pll;
typedef pair<string, int> psi;
typedef pair<string, string> pss;

const double PI = 3.14159265358979323846264338327;
const double E = exp(1);
const double eps = 1e-30;

const int INF = 0x3f3f3f3f;
const int maxn = 2e2 + 5;
const int MOD = 1e9 + 7;

int G[10][10];
int V[10];

int n, e;

void dfs(int x)
{
    V[x] = 1;
    printf("%d ", x);
    for (int i = 0; i < n; i++)
    {
        if (V[i] == 0 && G[x][i] == 1)
            dfs(i);
    }
}

queue <int>q;

void bfs()
{
    int len = q.size();
    for (int i = 0; i < len; i++)
    {
        int num = q.front();
        printf("%d ", num);
        q.pop();
        for (int j = 0; j < n; j++)
        {
            if (V[j] == 0 && G[num][j])
            {
                V[j] = 1;
                q.push(j);
            }
        }
    }
    if (q.size())
        bfs();
}

int main()
{
    CLR(G);
    CLR(V);
    scanf("%d%d", &n, &e);
    int x, y;
    for (int i = 0; i < e; i++)
    {
        scanf("%d%d", &x, &y);
        G[x][y] = 1;
        G[y][x] = 1;
    }
    for (int i = 0; i < n; i++)
    {
        if (V[i] == 0)
        {
            printf("{ ");
            dfs(i);
            printf("}\n");
        }
    }
    CLR(V);
    for (int i = 0; i < n; i++)
    {
        if (V[i] == 0)
        {
            printf("{ ");
            q.push(i);
            V[i] = 1;
            bfs();
            printf("}\n");
        }
    }
}






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