思想
1 从图中删除入度为0的顶点
2 删除以顶点为弧尾的边,并将弧头的入度减1
3 重复1,2步骤直到网为空或者网不存在无前驱的顶点(有环)
存储方式
使用领接表来存储图的相关信息,便于图中各顶点入度的求解。
具体实现
//DAG有向无环图的拓扑排序(采用邻接表存储)
package main
import "fmt"
//ArcNode is arc node
type ArcNode struct {
adjvex int
next *ArcNode
}
//VNode is vertex node
type VNode struct {
data int
first *ArcNode
}
//ALGraph is graph
type ALGraph struct {
vertices []VNode
vexnum, arcnum int
}
const vexnum = 5
var graphRelation [vexnum][5]int
var al ALGraph
var inDegree [vexnum]int
//入度为0的顶点
var emptyInDegreeVex []int
//最后的拓扑排序结果
var topologicalVex []int
func initGraphRelation() {
//有环图 vexnum = 6
// graphRelation[0][0] = 2
// graphRelation[0][1] = 4
// graphRelation[1][0] = 5
// graphRelation[2][0] = 6
// graphRelation[2][1] = 5
// graphRelation[3][0] = 2
// graphRe