-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathUnionFind.php
50 lines (41 loc) · 1.08 KB
/
UnionFind.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
<?php
declare(strict_types=1);
namespace leetcode\util;
class UnionFind
{
public $count = 0;
public $parent = [];
public function __construct(array $grid)
{
[$m, $n] = [count($grid), count($grid[0])];
$this->parent = new \SplFixedArray($m * $n);
for ($i = 0; $i < $m; $i++) {
for ($j = 0; $j < $n; $j++) {
if ($grid[$i][$j] === 1) {
$id = $i * $n + $j;
$this->parent[$id] = $id;
$this->count++;
}
}
}
}
public function find(int $node): int
{
if ($this->parent[$node] !== $node) {
$this->parent[$node] = $this->find($this->parent[$node]);
}
return $this->parent[$node];
}
public function union(int $x, int $y): void
{
[$rootx, $rooty] = [$this->find($x), $this->find($y)];
if ($rootx !== $rooty) {
$this->parent[$rootx] = $rooty;
$this->count--;
}
}
public function count(): int
{
return $this->count;
}
}