[leetcode] problem 329 – longest increasing path in a matrix

Given an integer matrix, find the length of the longest increasing path.

From each cell, you can either move to four directions: left, right, up or down. You may NOT move diagonally or move outside of the boundary (i.e. wrap-around is not allowed).

Example

No.1

Input: nums =

1
2
3
4
5
[
[9,9,4],
[6,6,8],
[2,1,1]
]

Output: 4

Explanation: The longest increasing path is [1, 2, 6, 9].

No.2

Input: nums =

1
2
3
4
5
[
[3,4,5],
[3,2,6],
[2,2,1]
]

Output: 4

Explanation: The longest increasing path is [3, 4, 5, 6]. Moving diagonally is not allowed.

Code

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
private int[][] dirs = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};

public int (int[][] matrix) {
int result = 0;

if (matrix == null || matrix.length == 0 || matrix[0].length == 0)
return result;

int m = matrix.length;
int n = matrix[0].length;
int[][] path = new int[m][n];

for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++)
result = Math.max(result, dfs(matrix, path, m, n, i, j));
}

return result;
}

private int dfs(int[][] matrix, int[][] path, int m, int n, int x, int y) {
if (path[x][y] != 0)
return path[x][y];

path[x][y] = 1;

for (int[] dir : dirs) {
int newX = x + dir[0];
int newY = y + dir[1];

if (newX < 0 || newY < 0 || newX >= m || newY >= n)
continue;

if (matrix[x][y] >= matrix[newX][newY])
continue;

path[x][y] = Math.max(path[x][y], 1 + dfs(matrix, path, m, n, newX, newY));
}

return path[x][y];
}