Topological Sort
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) } } }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· .NET10 - 预览版1新功能体验(一)