AvailableCapturesForRook::numRookCaptures()   B
last analyzed

Complexity

Conditions 7
Paths 10

Size

Total Lines 18
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
eloc 11
c 2
b 0
f 0
dl 0
loc 18
rs 8.8333
cc 7
nc 10
nop 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace leetcode;
6
7
class AvailableCapturesForRook
8
{
9
    public static function numRookCaptures(array $board): int
10
    {
11
        [$m, $n] = [count($board), empty($board[0]) ? 0 : count($board[0])];
12
        if ($m === 0 || $n === 0) {
13
            return 0;
14
        }
15
        for ($i = 0; $i < $m; $i++) {
16
            for ($j = 0; $j < $n; $j++) {
17
                if ($board[$i][$j] === 'R') {
18
                    return self::helper($board, $i, $j, 0, 1)
19
                        + self::helper($board, $i, $j, 0, -1)
20
                        + self::helper($board, $i, $j, 1, 0)
21
                        + self::helper($board, $i, $j, -1, 0);
22
                }
23
            }
24
        }
25
26
        return 0;
27
    }
28
29
    private static function helper(array $board, int $x, int $y, int $dx, int $dy): int
30
    {
31
        [$m, $n] = [count($board), empty($board[0]) ? 0 : count($board[0])];
32
        while ($x >= 0 && $x < $m && $y >= 0 && $y < $n && $board[$x][$y] !== 'B') {
33
            if ($board[$x][$y] === 'p') {
34
                return 1;
35
            }
36
            [$x, $y] = [$x + $dx, $y + $dy];
37
        }
38
39
        return 0;
40
    }
41
}
42