NumberOfIslands   A
last analyzed

Complexity

Total Complexity 11

Size/Duplication

Total Lines 27
Duplicated Lines 0 %

Importance

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

1 Method

Rating   Name   Duplication   Size   Complexity  
B numIslands() 0 23 11
1
<?php
2
3
declare(strict_types=1);
4
5
namespace leetcode;
6
7
use leetcode\util\UnionFind;
8
9
class NumberOfIslands
10
{
11
    private static $distance = [[-1, 0], [0, 1]];
12
13
    public static function numIslands(array $grid): int
14
    {
15
        [$rows, $cols] = [count($grid), count($grid[0])];
16
        if ($rows === 0) {
17
            return 0;
18
        }
19
20
        $uf = new UnionFind($grid);
21
        for ($i = 0; $i < $rows; $i++) {
22
            for ($j = 0; $j < $cols; $j++) {
23
                if ($grid[$i][$j] === 1) {
24
                    foreach (self::$distance as $item) {
25
                        [$x, $y] = [$i + $item[0], $j + $item[1]];
26
27
                        if ($x >= 0 && $x < $rows && $y >= 0 && $y < $cols && $grid[$x][$y] === 1) {
28
                            $uf->union($i * $cols + $j, $x * $cols + $y);
29
                        }
30
                    }
31
                }
32
            }
33
        }
34
35
        return $uf->count;
36
    }
37
}
38