MaximalSquare::maximalSquare3()   A
last analyzed

Complexity

Conditions 6
Paths 5

Size

Total Lines 21
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
eloc 14
c 2
b 0
f 0
dl 0
loc 21
rs 9.2222
cc 6
nc 5
nop 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace leetcode;
6
7
class MaximalSquare
8
{
9
    public static function maximalSquare(array $matrix): int
10
    {
11
        [$m, $n, $ans] = [count($matrix), count($matrix[0]), 0];
12
        if ($m <= 0 || $n <= 0) {
13
            return $ans;
14
        }
15
        $helper = static function (array $array, int $k) {
16
            $n = count($array);
17
            if ($n < $k) {
18
                return 0;
19
            }
20
            $counter = 0;
21
            for ($i = 0; $i < $n; $i++) {
22
                $counter = $array[$i] !== $k ? 0 : ($counter + 1);
23
                if ($counter === $k) {
24
                    return $k * $k;
25
                }
26
            }
27
28
            return 0;
29
        };
30
31
        for ($i = 0; $i < $m; $i++) {
32
            $tmp = array_fill(0, $n, 0);
33
            for ($j = $i; $j < $n; $j++) {
34
                for ($k = 0; $k < $n; $k++) {
35
                    if (isset($matrix[$j][$k]) && $matrix[$j][$k] === 1) {
36
                        $tmp[$k]++;
37
                    }
38
                }
39
                $ans = max($ans, $helper($tmp, $j - $i + 1));
40
            }
41
        }
42
43
        return $ans;
44
    }
45
46
    public static function maximalSquare2(array $matrix): int
47
    {
48
        [$m, $n, $ans] = [count($matrix), count($matrix[0]), 0];
49
        if ($m <= 0 || $n <= 0) {
50
            return 0;
51
        }
52
        $dp = array_fill(0, $m + 1, array_fill(0, $n + 1, 0));
53
        for ($i = 1; $i <= $m; $i++) {
54
            for ($j = 1; $j <= $n; $j++) {
55
                if ($matrix[$i - 1][$j - 1] === 1) {
56
                    $dp[$i][$j] = min($dp[$i - 1][$j - 1], min($dp[$i - 1][$j], $dp[$i][$j - 1])) + 1;
57
                    $ans = max($ans, $dp[$i][$j]);
58
                }
59
            }
60
        }
61
62
        return $ans * $ans;
63
    }
64
65
    public static function maximalSquare3(array $matrix): int
66
    {
67
        [$m, $n, $ans, $prev] = [count($matrix), count($matrix[0]), 0, 0];
68
        if ($m <= 0 || $n <= 0) {
69
            return 0;
70
        }
71
        $dp = array_fill(0, $m + 1, 0);
72
        for ($j = 0; $j < $n; $j++) {
73
            for ($i = 1; $i <= $m; $i++) {
74
                $temp = $dp[$i];
75
                if ($matrix[$i - 1][$j] === 1) {
76
                    $dp[$i] = min($dp[$i], min($dp[$i - 1], $prev)) + 1;
77
                    $ans = max($ans, $dp[$i]);
78
                } else {
79
                    $dp[$i] = 0;
80
                }
81
                $prev = $temp;
82
            }
83
        }
84
85
        return $ans * $ans;
86
    }
87
}
88