golang 实现并查集

该博客介绍了一种使用并查集算法来检测图中环路的方法。通过初始化数据,遍历图的边并应用`union`函数判断是否形成环路,如果检测到环路则输出提示并退出程序,否则表明图中没有环路。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

package main

import (
	"fmt"
	"os"
)

const SIZE =6


//找到根节点
func findRoot(x int,data []int)int  {
	root :=x
	if data[root]==-1{
		return root
	} else {
		root = findRoot(data[root],data)
		return root
	}
}

// 0 表示有环了
func union(x int,y int,data []int,rank []int) int {
	xRoot := findRoot(x,data)
	yRoot := findRoot(y,data)
	if xRoot ==yRoot{
		return 0
	}else {
		if rank[xRoot]>rank[yRoot]{
			data[yRoot] = xRoot
			rank[xRoot] +=1
		}else {
			data[xRoot] = yRoot
			rank[yRoot] +=1
		}
		return 1
	}

}

func initData(data []int,rank []int){
	for index:=0;index<SIZE;index++{
		data[index] =-1
		rank[index] =0
	}
}

func main() {
	data := make([]int,SIZE)
	rank :=make([]int,SIZE)
	initData(data,rank)
	graph :=[6][2]int{
		{0,1},{1,2},{1,3},{3,4},{2,5},
		{5,4},
	}
	for i:=0;i<SIZE;i++{
		res := union(graph[i][0],graph[i][1],data,rank)
		if res==0{
			fmt.Println("cycle detect")
			os.Exit(1)
		}
	}
	fmt.Println("no cycle")


}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值