MinCostToConnectAllPoints   A
last analyzed

Complexity

Total Complexity 7

Size/Duplication

Total Lines 27
Duplicated Lines 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
wmc 7
eloc 19
c 2
b 0
f 0
dl 0
loc 27
rs 10

1 Method

Rating   Name   Duplication   Size   Complexity  
B minCostConnectPoints() 0 25 7
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