图的遍历

#include<iostream>
#include<cstdio>
#include<cstring>

using namespace std;
#define N 110

typedef struct{
    char vexs[N];
    int edge[N][N];
    int n, e;
}matrix_graph;

int vis[N], cnt;

void creatMG(matrix_graph &g)
{
    int u, v;
    scanf("%d%d", &g.n, &g.e);
    getchar();
    for(int i=1; i<=g.n; i++)
        for(int j=1; j<g.n; j++)
        g.edge[i][j]=0;
    for(int i=0; i<g.n; i++)
        scanf("%c", &g.vexs[i]);
    getchar();
    for(int i=0; i<g.e; i++)
    {
        scanf("%d%d", &u, &v);
        g.edge[u][v]=g.edge[v][u]=1;
    }
}

void DFS(matrix_graph g, int u)
{
    vis[u]=1;
    for(int i=1; i<=g.n; i++)
    {
        if(!vis[i]&&g.edge[u][i])
            DFS(g, i);
    }
}

void DFSM(matrix_graph g)
{
    for(int i=1; i<=g.n; i++)
    if(!vis[i])
    {
        cnt++;
        DFS(g, i);
    }
}

int main()
{
    matrix_graph g;
    memset(vis, 0, sizeof(vis));
    cnt=0;
    creatMG(g);
    DFSM(g);
    printf("%d
", cnt);
    return 0;
}
原文地址:https://www.cnblogs.com/9968jie/p/6110948.html