FriendCircles::findCircleNum()   B
last analyzed

Complexity

Conditions 7
Paths 11

Size

Total Lines 24
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
eloc 15
c 2
b 0
f 0
dl 0
loc 24
rs 8.8333
cc 7
nc 11
nop 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace leetcode;
6
7
class FriendCircles
8
{
9
    public static function findCircleNum(array $grid): int
10
    {
11
        $n = count($grid);
12
        if ($n === 0) {
13
            return 0;
14
        }
15
        $root = array_fill(0, $n, 0);
16
        for ($i = 0; $i < $n; $i++) {
17
            $root[$i] = $i;
18
        }
19
        $cnt = $n;
20
        for ($i = 0; $i < $n; $i++) {
21
            for ($j = $i + 1; $j < $n; $j++) {
22
                if ($grid[$i][$j] === 1) {
23
                    [$x, $y] = [self::findRoot($root, $i), self::findRoot($root, $j)];
24
                    if ($x !== $y) {
25
                        $root[$x] = $y;
26
                        $cnt--;
27
                    }
28
                }
29
            }
30
        }
31
32
        return $cnt;
33
    }
34
35
    private static function findRoot(array $root, int $id): int
36
    {
37
        return $root[$id] !== $id ? self::findRoot($root, $root[$id]) : $id;
38
    }
39
}
40