(逆)拓扑排序DFS实现

// 逆拓扑排序DFS实现.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//

#include <iostream>
#include <queue>
#include<stack>
#include <cstring> // for memset
#define Max 503
#define INF 0xcffff

using namespace std;

typedef struct AMGraph {
    int vex, arc;
    int arcs[Max][Max];
} AMGraph;

bool visited[Max];
stack<int>zhan;
queue<int>q;

int firstnode(AMGraph& G, int x) {
    for (int i = 1; i <= G.vex; i++) {
        if (G.arcs[x][i] > 0 && !visited[i])
            return i;
    }
    return -1;
}

int nextnode(AMGraph& G, int x, int next) {
    for (int i = next + 1; i <= G.vex; i++) {
        if (G.arcs[x][i] > 0 && !visited[i])
            return i;
    }
    return -1;
}

void DFS(AMGraph& G, int x) {
    visited[x] = true;
    for (int w = firstnode(G, x); w >= 0; w = nextnode(G, x, w))
        if (!visited[w])
            DFS(G, w);
    zhan.push(x);
    q.push(x);
    /*cout << x << " ";*/
}

void DFSTraverse(AMGraph& G) {
    for (int i : visited)
        visited[i] = false;
    int count = 0;
    for (int i = 1; i <= G.vex; i++) {
        if (!visited[i]) {
            cout <<"入点" << i << " "<<endl;
            DFS(G, i);
            count++;
        }
    }
    cout << "\n连通分量数为:" << count << endl;
}

void putin(AMGraph& G) {
    int u, v;
    cin >> G.vex >> G.arc;

    for (int i = 1; i <= G.vex; i++) {
        for (int j = 1; j <= G.vex; j++) {
            if (i == j) G.arcs[i][j] = 0;
            else G.arcs[i][j] = -1; // 初始化为-1,表示无边
        }
    }

    for (int i = 0; i < G.arc; i++) {
        cin >> u >> v;
        G.arcs[u][v] = 1;
    }
}

int main() {
    AMGraph G;
    putin(G);
    DFSTraverse(G);
    cout << "拓扑排序是:";
    while (!zhan.empty()) {
        cout << zhan.top() << " ";
        zhan.pop();
    }
    cout << "\n逆拓扑排序是:";
    while (!q.empty()) {
        cout << q.front() << " ";
        q.pop();
    }
    return 0;
}

/*
5 7
2 5
2 4
2 1
3 1
5 3
4 5
4 3
*/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值