基本图算法之拓扑排序 AOV网

图的拓扑排序内容比较简单,我们只要知道AOV网是一种
以顶点表示活动、以边表示活动先后顺序且没有回路的有向图即可。  拓扑排序有两种算法第一种Kahn算法,第二种基于DFS的算法,两种算法思想都比较简单,不详细介绍思想,其中需要注意的是
基于DFS的拓扑排序算法必需保证图是不存在环的!文章结尾放上两种算法的运行时间比较。 下面展示两种算法实现的部分代码,完整代码点击[github/tianzhuwei](https://github.com/tianzhuwei/-_-/tree/master/Introduction%20to%20Algorithms/Graph%20Algorithms/Topological%20Sort):

//第一种Kahn算法
void Graph::Kahn(){
    int n=0;//用来记录输出的顶点的个数;
    int* stack;
    stack=new int[vexNum];
    int top=-1;
    Edge* p=NULL;
    for (int i=0;i<vexNum;++i)
    {//将入度为0的顶点入栈;
        if (head[i].incount==0)
        {
            stack[++top]=i;
        }
    }//for;

    while(top!=-1){
        n++;
        int temp1,temp2;
        temp1=stack[top--];
        p=head[temp1].firstEdge;
        while(p!=NULL){
            temp2=--(head[p->vexName].incount);
            if (temp2==0)
            {
                stack[++top]=p->vexName;
            }
            p=p->next;
        }//while;
    }//while;
    if (n==vexNum)
    {
        cout<<"success"<<endl;
    }else{
        cout<<"fail"<<endl;
    }
}

***

//第二种基于DFS的拓扑排序算法
void Graph::DFS(int v){
        head[v].visit=1;
        Edge* p=NULL;
        p=head[v].firstEdge;
        while(p!=NULL){///////////注意:必需不能存在环;
            if (head[p->vexName].visit==0)
            {       
                DFS(p->vexName);
            }
            p=p->next;
        }
        //采用头插法输出顶点;
        //在这里输出;
}

void Graph::Under_DFS(){
    for (int i=0;i<vexNum;++i)
    {
        if (head[i].visit==0)
        {
            DFS(i);
        }

    }
}

****
《基本图算法之拓扑排序 AOV网》

暂时需要整理的就这么多,后期遇到总是再增加。^_^

    原文作者:拓扑排序
    原文地址: https://blog.csdn.net/wei_tianzhu/article/details/52059522
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞