java判断无向图是否有环_使用并查集判断无向图里是否存在环

记录一下。

使用并查集的方法判断无向图里是否存在环。

class UnionFind

{

private $parent = [];

public function __construct($n)

{

for ($i = 0; $i < $n; $i++) {

$this->parent[$i] = $i;

}

}

public function find($x)

{

while ($x != $this->parent[$x]) {

$this->parent[$x] = $this->parent[$this->parent[$x]];

$x = $this->parent[$x];

}

return $x;

}

public function union($x, $y)

{

$rootX = $this->find($x);

$rootY = $this->find($y);

if ($rootX == $rootY) {

return false;

}

$this->parent[$rootX] = $rootY;

return true;

}

}

function hasCycle()

{

$uf = new UnionFind(5);

$edges = [[1, 2], [2, 3], [3, 4], [4,1]];

foreach ($edges as $edge) {

$from = $edge[0];

$to = $edge[1];

if ($uf->union($from, $to) === false) {

echo "Cycle detected!";

}

}

echo "No cycle!";

}

复制代码

为什么不能判断有向图,应该是有比如下面这种情况,如果按上面的代码,会判断为有环,实际上这是无环。

62a1df792fda4058f4861b01c178e4e9.png

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值