-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path329.php
More file actions
55 lines (42 loc) · 1.22 KB
/
329.php
File metadata and controls
55 lines (42 loc) · 1.22 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
<?php
class Solution {
public $visited = [];
/**
* @param Integer[][] $matrix
* @return Integer
*/
function longestIncreasingPath($matrix)
{
if (!$matrix) return 0;
$len = 1;
$width = count($matrix);
$height = count($matrix[0]);
for ($i = 0; $i < $width; $i ++) {
for ($j = 0; $j < $height; $j ++) {
$len = max($len, $this->dfs($matrix, $i, $j));
}
}
return $len;
}
function dfs($m, $i, $j)
{
if (isset($this->visited[$i][$j])) return $this->visited[$i][$j];
$x = [$i - 1, $i, $i + 1, $i];
$y = [$j, $j - 1, $j, $j + 1];
$width = count($m);
$height = count($m[0]);
$len = 1;
for ($k = 0; $k < 4; $k ++) {
if ($x[$k] < 0 || $y[$k] < 0 || $x[$k] > $width - 1 || $y[$k] > $height - 1 || $m[$x[$k]][$y[$k]] <= $m[$i][$j]) {
continue;
}
$len = max($len, $this->dfs($m, $x[$k], $y[$k]) + 1);
}
$this->visited[$i][$j] = $len;
return $len;
}
}
$m = [[9,9,4],[6,6,8],[2,1,1]];
$m = [[0],[1],[5],[5]];
$sol = new Solution();
var_dump($sol->longestIncreasingPath($m));