NQueens   A
last analyzed

Complexity

Total Complexity 13

Size/Duplication

Total Lines 45
Duplicated Lines 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
wmc 13
eloc 24
c 2
b 0
f 0
dl 0
loc 45
rs 10

2 Methods

Rating   Name   Duplication   Size   Complexity  
B isAttackedRange() 0 26 9
A solveNQueens() 0 15 4
1
<?php
2
3
declare(strict_types=1);
4
5
namespace leetcode;
6
7
use leetcode\util\Position;
8
9
class NQueens
10
{
11
    public static function solveNQueens(int $n): array
12
    {
13
        if ($n == 0) {
14
            return [];
15
        }
16
        $positions = [];
17
        for ($i = 0; $i < $n; $i++) {
18
            $positions[$i] = new Position();
19
        }
20
21
        if (self::isAttackedRange($n, 0, $positions)) {
22
            return $positions;
23
        }
24
25
        return $positions;
26
    }
27
28
    private static function isAttackedRange(int $n, int $row, &$positions): bool
29
    {
30
        if ($n === $row) {
31
            return true;
32
        }
33
34
        for ($col = 0; $col < $n; $col++) {
35
            $isSafe = true;
36
            for ($queen = 0; $queen < $row; $queen++) {
37
                if ($positions[$queen]->col === $col
38
                    || $positions[$queen]->row - $positions[$queen]->col === $row - $col
39
                    || $positions[$queen]->row + $positions[$queen]->col === $row + $col) {
40
                    $isSafe = false;
41
                    break;
42
                }
43
            }
44
45
            if ($isSafe) {
46
                $positions[$row] = new Position($row, $col);
47
                if (self::isAttackedRange($n, $row + 1, $positions)) {
48
                    return true;
49
                }
50
            }
51
        }
52
53
        return false;
54
    }
55
}
56