输出该无向图中连通分量的个数

通过计算调用DFS的次数来记录该无向图中连通分量的个数

#include<bits/stdc++.h>
using namespace std;
typedef struct Arcnode {
    int adjvex;
    struct Arcnode* nextarc;
}Arcnode;
typedef struct Vnode {
    int data;
    Arcnode* firstarc;
}Vnode,AdjList[1024];
typedef struct ALGraph {
    int vexnum, arcnum;
    AdjList vertices;
}ALGraph;

int visited[1024] = { 0 };
int num = 0;
void DFS(ALGraph G, int u) {
    Arcnode* s[1024] = { 0 };
    int top = -1;
    num++;
    s[++top] = G.vertices[u].firstarc;
    visited[u] = 1;
    while (top != -1) {
        Arcnode* p = s[top];
        while (p != NULL) {
            if (visited[p->adjvex] == 0) {
                s[++top] = G.vertices[p->adjvex].firstarc;
                visited[p->adjvex] = 1;
                break;
            }
            p = p->nextarc;
        }
        if (p == NULL) top--;
    }
}
void DFSTrave(ALGraph G, int n) {
    int i;
    for (i = 1; i <= n; i++) {
        if (visited[i] == 0)
            DFS(G, i);
    }
    cout << num;
}
void create(ALGraph& G) {
    cin >> G.vexnum >> G.arcnum;
    int i;
    for (i = 1; i <= G.vexnum; i++) {
        cin >> G.vertices[i].data;
        G.vertices[i].firstarc = NULL;
    }
    for (i = 1; i <= G.arcnum; i++) {
        Arcnode* p = new Arcnode;
        Arcnode* q = new Arcnode;
        cin >> p->adjvex >> q->adjvex;
        q->nextarc = G.vertices[p->adjvex].firstarc;
        G.vertices[p->adjvex].firstarc = q;
        p->nextarc = G.vertices[q->adjvex].firstarc;
        G.vertices[q->adjvex].firstarc = p;
    }
}
int main() {
    ALGraph G;
    create(G);
    DFSTrave(G, G.vexnum);
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值