Go语言实现拓扑排序(Topological Sorting)算法

 在Go语言中实现拓扑排序也可以使用Kahn's算法,步骤和Python版本的实现类似。以下是一个完整的Go语言实现:

package main

import (
	"fmt"
)

// topologicalSort performs a topological sort on a directed graph.
// numCourses is the number of courses, and prerequisites is a list of prerequisite pairs.
func topologicalSort(numCourses int, prerequisites [][]int) []int {
	// Create an adjacency list and an in-degree array
	adjList := make(map[int][]int)
	inDegree := make([]int, numCourses)

	// Populate the adjacency list and in-degree array
	for _, prereq := range prerequisites {
		dest, src := prereq[0], prereq[1]
		adjList[src] = append(adjList[src], dest)
		inDegree[dest]++
	}

	// Initialize a queue with all nodes having in-degree of 0
	queue := []int{}
	for i := 0; i < numCourses; i++ {
		if inDegree[i] == 0 {
			queue = append(queue, i)
		}
	}

	var topologicalOrder []int

	// Process until the queue becomes empty
	for len(queue) > 0 {
		vertex := queue[0]
		queue = queue[1:]
		topologicalOrder = append(topologicalOrder, vertex)

		// For each neighbor, reduce its in-degree by 1
		for _, neighbor := range adjList[vertex] {
			inDegree[neighbor]--
			// If in-degree becomes 0, add it to the queue
			if inDegree[neighbor] == 0 {
				queue = append(queue, neighbor)
			}
		}
	}

	// Check if topological sort is possible or not
	if len(topologicalOrder) == numCourses {
		return topologicalOrder
	} else {
		return []int{} // Return an empty list if there is a cycle in the graph
	}
}

func main() {
	numCourses := 6
	prerequisites := [][]int{
		{5, 2},
		{5, 0},
		{4, 0},
		{4, 1},
		{2, 3},
		{3, 1},
	}

	result := topologicalSort(numCourses, prerequisites)
	fmt.Println(result)
}

这个Go语言实现的步骤如下:

  1. 创建邻接表(adjList)和入度数组(inDegree)。
  2. 遍历所有边,填充邻接表和入度数组。
  3. 将所有入度为0的节点加入队列。
  4. 依次处理队列中的节点,更新其邻接节点的入度,并将新的入度为0的节点加入队列。
  5. 最终,如果排序结果中的节点数量等于图中的节点数,则返回拓扑排序结果;否则,说明图中有环,返回空列表。

这个实现假设输入是一个表示课程和先修课程的有向无环图(DAG),并返回一个可能的课程安排顺序。如果图中存在环,则返回空列表。

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Python拓扑排序可以通过使用深度优先搜索(DFS)算法实现。有两种常见的实现方法。 第一种方法是使用递归的方式实现。在这种方法中,我们定义一个递归函数`topoSortvisit0`,它接受三个参数:当前节点`s`,访问状态列表`visited`和排序列表`sortlist`。首先,将当前节点标记为已访问。然后,对于当前节点的每个邻接节点,在邻接节点未被访问的情况下,递归调用`topoSortvisit0`函数。最后,将当前节点插入到排序列表的开头。接着,我们定义`topoSortDfs0`函数,初始化节点的访问状态列表`visited`和排序列表`sortlist`,然后对于图中的每个节点,如果节点未被访问,就调用`topoSortvisit0`函数。最后,返回排序列表即可得到拓扑排序的结果。 第二种方法是使用堆栈来实现。在这种方法中,我们定义一个辅助函数`topologicalSortUtil`,它接受三个参数:当前节点`v`,访问状态列表`visited`和堆栈`stack`。首先,将当前节点标记为已访问。然后,对于当前节点的每个邻接节点,如果邻接节点未被访问,就递归调用`topologicalSortUtil`函数。最后,将当前节点插入到堆栈的开头。接着,我们定义`topologicalSort`函数,初始化节点的访问状态列表`visited`和堆栈`stack`,然后对于图中的每个节点,如果节点未被访问,就调用`topologicalSortUtil`函数。最后,输出堆栈的内容即可得到拓扑排序的结果。 综上所述,可以使用上述两种方法之一来实现Python拓扑排序。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* [拓扑排序(topological sorting)介绍及Python实现](https://blog.csdn.net/chenxy_bwave/article/details/125074013)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] - *3* [拓扑排序Python实现](https://blog.csdn.net/JohnJim0/article/details/121047511)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值