前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >原 初学图论-Kahn拓扑排序算法(Kah

原 初学图论-Kahn拓扑排序算法(Kah

作者头像
不高不富不帅的陈政_
发布2018-05-18 10:15:40
1K0
发布2018-05-18 10:15:40
举报
文章被收录于专栏:聊聊技术聊聊技术

    笔者使用了较为方便的邻接链表表示法。如果使用邻接矩阵,可能需要平方量级的时间消耗。

    为了实现的方便,笔者使用了STL库中的队列结构。当队列为空时终止循环,此时如果仍然有边存在,则说明图中存在环,没有拓扑顺序。

    代码如下:

代码语言:javascript
复制
/**
 * The Kahn's Topological Sort Algorithm in C++
 * Using the Adjecency List
 * Time Cost : O(|V|+|E|)
 * Author: Zheng Chen / Arclabs001
 * Copyright 2015 Xi'an University of Posts & Telecommunications
 */
#include <iostream>
#include <queue>
#include <vector>
using namespace std;

const int N = 5; // The number of Vertex

enum status {UNDISCOVERED,VISITED};

struct Vertex
{
    int inDegree, outDegree;
    int data;
    status _stat;
}V[N];

vector<int> AdjList[N];   //Using vector to simulate the adjlist
queue<int> vertexQueue;   //The call queue
/**
 * Initialize the graph as below:
The Graph:

0->1->3
|  |  |
\/ \/ \/
2->4<--

 * @return The pointer to the start vertex
 */
Vertex* init_graph()
{
    while(!vertexQueue.empty())
        vertexQueue.pop();

    for(int i=0; i<N; i++)
    {
        AdjList[i].clear();
        V[i]._stat = UNDISCOVERED;
        V[i].data = i;
    }

    V[0].inDegree = 0; V[0].outDegree = 2;
    V[1].inDegree = 1; V[1].outDegree = 3;
    V[2].inDegree = 1; V[2].outDegree = 1;
    V[3].inDegree = 1; V[3].outDegree = 1;
    V[4].inDegree = 3; V[4].outDegree = 0;

    AdjList[0].push_back(1); AdjList[0].push_back(2);
    AdjList[1].push_back(3); AdjList[1].push_back(4);
    AdjList[2].push_back(4);
    AdjList[3].push_back(4);

    return & V[0];
}

bool Topological_Sort()
{
    for(int i=0; i<N; i++)
    {
        if(V[i].inDegree == 0)
            vertexQueue.push(i);
    }

    while(!vertexQueue.empty())
    {
        int top = vertexQueue.front();
        V[top].outDegree = 0;
        V[top]._stat = VISITED;
        int i=0;

        for(int v : AdjList[top])
        {
            --V[v].inDegree;

            AdjList[top][i++] = -1;
            if(V[v].inDegree == 0)
                vertexQueue.push(v);
        }
        cout<<top<<" ";

        vertexQueue.pop();
    }

    for(int i=0; i<N; i++)
    {
        for(int v : AdjList[i])
            if(v != -1)
            {
                return false;
            }
    }

    return true;
}

int main()
{
    init_graph();

    bool status = Topological_Sort();
    if(status == false)
    {
        cout<<"Error! The graph has at least one cycle!"<<endl;
    }
    return 0;
}

谢谢观看~

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档