-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathFriendCircles.php
39 lines (34 loc) · 929 Bytes
/
FriendCircles.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
<?php
declare(strict_types=1);
namespace leetcode;
class FriendCircles
{
public static function findCircleNum(array $grid): int
{
$n = count($grid);
if ($n === 0) {
return 0;
}
$root = array_fill(0, $n, 0);
for ($i = 0; $i < $n; $i++) {
$root[$i] = $i;
}
$cnt = $n;
for ($i = 0; $i < $n; $i++) {
for ($j = $i + 1; $j < $n; $j++) {
if ($grid[$i][$j] === 1) {
[$x, $y] = [self::findRoot($root, $i), self::findRoot($root, $j)];
if ($x !== $y) {
$root[$x] = $y;
$cnt--;
}
}
}
}
return $cnt;
}
private static function findRoot(array $root, int $id): int
{
return $root[$id] !== $id ? self::findRoot($root, $root[$id]) : $id;
}
}