ValidSudoku::isValidSudoku()   B
last analyzed

Complexity

Conditions 10
Paths 6

Size

Total Lines 25
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
eloc 16
c 2
b 0
f 0
dl 0
loc 25
rs 7.6666
cc 10
nc 6
nop 1

How to fix   Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
declare(strict_types=1);
4
5
namespace leetcode;
6
7
class ValidSudoku
8
{
9
    public static function isValidSudoku(array $board): bool
10
    {
11
        [$m, $n] = [count($board), count($board[0])];
12
        if ($m === 0 || $n === 0) {
13
            return false;
14
        }
15
        $helper = static function (array &$array, int $k, int $v) {
16
            $array[$k][$v] = isset($array[$k][$v]) ? $array[$k][$v] + 1 : 1;
17
        };
18
        $row = $col = $box = array_fill(0, $m, array_fill(0, $n, 0));
19
        for ($i = 0; $i < $m; $i++) {
20
            for ($j = 0; $j < $n; $j++) {
21
                if ('.' !== $v = $board[$i][$j]) {
22
                    [$v, $k] = [(int) $v, (int) (floor($i / 3) * 3 + floor($j / 3))];
23
                    $helper($row, $i, $v);
24
                    $helper($col, $j, $v);
25
                    $helper($box, $k, $v);
26
                    if ($row[$i][$v] > 1 || $col[$j][$v] > 1 || $box[$k][$v] > 1) {
27
                        return false;
28
                    }
29
                }
30
            }
31
        }
32
33
        return true;
34
    }
35
}
36