NQueensII   A
last analyzed

Complexity

Total Complexity 9

Size/Duplication

Total Lines 36
Duplicated Lines 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
wmc 9
eloc 16
c 2
b 0
f 0
dl 0
loc 36
rs 10

3 Methods

Rating   Name   Duplication   Size   Complexity  
A totalNQueens() 0 6 1
A helper() 0 15 4
A isAttackedRange() 0 9 4
1
<?php
2
3
declare(strict_types=1);
4
5
namespace leetcode;
6
7
class NQueensII
8
{
9
    public static function totalNQueens(int $n): int
10
    {
11
        $num = 0;
12
        $chessboard = array_fill(0, $n, 0);
13
14
        return self::helper($chessboard, 0, $num);
15
    }
16
17
    private static function helper(array &$chessboard, int $row, int &$num): int
18
    {
19
        if ($row === $count = count($chessboard)) {
20
            $num++;
21
        }
22
23
        for ($col = 0; $col < $count; $col++) {
24
            if (self::isAttackedRange($chessboard, $row, $col)) {
25
                $chessboard[$row] = $col;
26
                self::helper($chessboard, $row + 1, $num);
27
                $chessboard[$row] = 0;
28
            }
29
        }
30
31
        return $num;
32
    }
33
34
    public static function isAttackedRange(array &$chessboard, int $row, int $col): bool
35
    {
36
        for ($i = 0; $i < $row; $i++) {
37
            if ($col === $chessboard[$i] || abs($row - $i) === abs($col - $chessboard[$i])) {
38
                return false;
39
            }
40
        }
41
42
        return true;
43
    }
44
}
45