记录一下。
使用并查集的方法判断无向图里是否存在环。
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!";
}
复制代码
为什么不能判断有向图,应该是有比如下面这种情况,如果按上面的代码,会判断为有环,实际上这是无环。