MinCostToConnectAllPoints::minCostConnectPoints()   B
last analyzed

Complexity

Conditions 7
Paths 10

Size

Total Lines 25
Code Lines 18

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
eloc 18
c 2
b 0
f 0
dl 0
loc 25
rs 8.8333
cc 7
nc 10
nop 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace leetcode;
6
7
class MinCostToConnectAllPoints
8
{
9
    public static function minCostConnectPoints(array $points): int
10
    {
11
        [$m, $n] = [count($points), is_array($points[0]) ? count($points[0]) : 0];
12
        if ($m <= 0 || $n <= 0) {
13
            return 0;
14
        }
15
        $ans = $key = 0;
16
        [$dist, $seen] = [array_fill(0, $m, PHP_INT_MAX), []];
17
        for ($i = 0; $i < $m - 1; $i++) {
18
            [$x, $y] = $points[$key];
19
            $seen[$key] = 1;
20
            foreach ($points as $j => $point) {
21
                if (isset($seen[$j])) {
22
                    continue;
23
                }
24
                [$p, $q] = $point;
25
                $dist[$j] = min($dist[$j], abs($p - $x) + abs($q - $y));
26
            }
27
            $val = min($dist);
28
            $key = array_search($val, $dist);
29
            $dist[$key] = PHP_INT_MAX;
30
            $ans += $val;
31
        }
32
33
        return $ans;
34
    }
35
}
36