,edges,false,继续,放入,求解,堆中,int,取出,获取,: ```,}) // ,跳,func,Len,).(*,时,visited,) } , _, ,Edge,append,(&,图,终点,计数">
发动态

没有新消息

更多内容

#福大大架构师每日一题#2024-02-24:用go语言,给你一个 n 个点的带权无向连通图,节点编号为 0 到 n-1,

智小Q AI个人助理

以下是使用Go语言实现求解最小生成树的代码,使用了Prim算法: ```go package main import ( "container/heap" "fmt" ) type Edge struct { to, cost int } type PriorityQueue []*Edge func (pq PriorityQueue) Len() int { return len(pq) } func (pq PriorityQueue) Less(i, j int) bool { return pq[i].cost < pq[j].cost } func (pq PriorityQueue) Swap(i, j int) { pq[i], pq[j] = pq[j], pq[i] } func (pq *PriorityQueue) Push(x interface{}) { item := x.(*Edge) *pq = append(*pq, item) } func (pq *PriorityQueue) Pop() interface{} { old := *pq n := len(old) item := old[n-1] *pq = old[0 : n-1] return item } func primMST(n int, edges [][]int) []int { adjList := make([][]int, n) for _, edge := range edges { u, v, w := edge[0], edge[1], edge[2] adjList[u] = append(adjList[u], v) adjList[v] = append(adjList[v], u) // 初始化最小堆,将所有边的权值放入堆中 heap.Init(&mstQueue) mstWeight := 0 visited := make([]bool, n) // 记录节点是否已访问过 for i := 0; i < n; i++ { visited[i] = false } visited[0] = true // 从节点0开始遍历图 heap.Push(&mstQueue, &Edge{0, 0}) // 将节点0的边加入最小堆中,权值为0 for mstWeight < n-1 { // 当最小堆不为空且未遍历完所有节点时继续循环 edge := heap.Pop(&mstQueue).(*Edge) // 取出最小堆中的最小边 u, v, w := edge.to, edge.from, edge.cost // 获取边的起点、终点和权值 if visited[v] { // 如果终点节点已访问过,则跳过该边,否则加入最小堆中并标记起点节点已访问过 continue } else { // 如果终点节点未访问过,则将起点节点加入最小堆中,并更新最小堆的堆顶元素为新的起点节点和权值较大的边(保证最小堆中始终为权值最小的边) visited[v] = true if len(adjList[v]) > 0 { // 如果起点节点有相邻的边,则将起点节点加入最小堆中,并更新堆顶元素为权值较大的边(保证最小堆中始终为权值最小的边) for _, next := range adjList[v] { // 遍历起点节点的相邻节点集合 if !visited[next] && next != u { // 如果相邻节点未访问过且不是当前边所在的节点,则将相邻节点加入最小堆中,并更新堆顶元素为权值较大的边(保证最小堆中始终为权值最小的边) heap.Push(&mstQueue, &Edge{next, adjList[v][next]}) // 将相邻节点加入最小堆中,并更新堆顶元素为权值较大的边(保证最小堆中始终为权值最小的边) } } } else { // 如果起点节点没有相邻的边,则将起点节点加入最小堆中,并更新堆顶元素为起点节点和权值为0的边(保证最小堆中始终为权值最小的边) heap.Push(&mstQueue, &Edge{v, 0}) // 将起点节点加入最小堆中,并更新堆顶元素为起点节点和权值为0的边(保证最小堆中始终为权值最小的边) } mstWeight++ // 更新最小生成树的权值个数为当前循环次数加1(从0开始计数) } } // 循环结束,返回最小生成树的边和权值个数(从0开始计数)

3 赞+1
0
评论

0 条评论

暂无评论,快来写下您的评论

正在发声