标签:dir val ons ring rap cli create lin const
package _Sort.Algorithm.topological_sort /** * Topological Sort is for Directed Acyclic Graph(DAG,有向无环图) * A DAG Graph has least one vertex with in-degree 0 and one vertex with out-degree 0. * 入度(in-degree):进入该节点的边的条数 * 出度(out-degree):从该节点出发的边的条数 * 1. we need paint a vertex before its adjacent vertex; * 2. we can use DFS or BFS * */ class DirectedGraphNode constructor(x: Int, neighbors: ArrayList<DirectedGraphNode>) { var label = 0 var neighbors: ArrayList<DirectedGraphNode>? = null init { this.label = x this.neighbors = neighbors } } class TopologicalSort { fun test() { val g = Graph(6) g.addEdge(5, 2) g.addEdge(5, 0) g.addEdge(4, 0) g.addEdge(4, 1) g.addEdge(2, 3) g.addEdge(3, 1) println("Following is a Topological Sort: ") g.topologicalSort() } }
Graph:
package _Sort.Algorithm.topological_sort import java.util.* import kotlin.collections.ArrayList class Graph constructor(v: Int) { private var V = 0//number of vertices private var adjacents: Array<ArrayList<Int>>? = null init { this.V = v adjacents = Array(V) { ArrayList<Int>() } for (i in 0 until V) { adjacents!![i] = ArrayList<Int>() } } /** * add edge to graph * */ fun addEdge(u: Int, v: Int) { if (adjacents != null) { adjacents!![u].add(v) } } fun topologicalSort() { //create array to store all indegrees of all vertices val inDegrees = IntArray(V) for (i in 0 until V) { val temp = adjacents!![i] for (node in temp) { inDegrees[node]++ } } //create queue and enqueue all vertices with indegree is 0 val queue = LinkedList<Int>() for (i in 0 until V) { if (inDegrees[i] == 0) { queue.offer(i) } } //count of visited vertex var countOfVisited = 0 val topOrder = ArrayList<Int>() //bfs while (queue.isNotEmpty()) { val cur = queue.poll() topOrder.add(cur) /*Iterate through all its neighbouring nodes of dequeued node u and decrease their in-degree by 1*/ for (node in adjacents!![cur]) { //if in-degree becomes 0, add it into queue if (--inDegrees[node] == 0) { queue.add(node) } } countOfVisited++ } //check if there waw cycle if (countOfVisited != V) { println("There exists a cycle in the graph") return } for (item in topOrder) { println(item) } } }
标签:dir val ons ring rap cli create lin const
原文地址:https://www.cnblogs.com/johnnyzhao/p/12979788.html