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 1:
nums = [ [9,9,4], [6,6,8], [2,1,1] ]
Return 4
The longest increasing path is [1, 2, 6, 9]
.
Example 2:
nums = [ [3,4,5], [3,2,6], [2,2,1] ]
Return 4
The longest increasing path is [3, 4, 5, 6]
. Moving diagonally is not allowed.
使用记忆化搜索
参考 https://www.hrwhisper.me/leetcode-longest-increasing-path-matrix/
public class Solution
{
public int LongestIncreasingPath(int[,] matrix)
{
int m = (int)matrix.GetLongLength(0);
int n = (int)matrix.GetLongLength(1);
if(m*n==0)
return 0;
int max=1;
int[,] dis = new int[m, n];
for (int i = 0; i < m; i++)
for (int j = 0; j < n; j++)
max = Math.Max(max, dfs(matrix, dis, m, n, i, j));
return max;
}
private int dfs(int[,] matrix, int[,] dis, int m, int n, int i, int j)
{
if (dis[i, j] != 0)
return dis[i, j];
if (j > 0 && matrix[i, j - 1] > matrix[i, j])
dis[i, j] = Math.Max(dis[i, j], dfs(matrix, dis, m, n, i, j - 1));
if (i > 0 && matrix[i - 1, j] > matrix[i, j])
dis[i, j] = Math.Max(dis[i, j], dfs(matrix, dis, m, n, i - 1, j));
if (j < n - 1 && matrix[i, j + 1] > matrix[i, j])
dis[i, j] = Math.Max(dis[i, j], dfs(matrix, dis, m, n, i, j + 1));
if (i < m - 1 && matrix[i + 1, j] > matrix[i, j])
dis[i, j] = Math.Max(dis[i, j], dfs(matrix, dis, m, n, i + 1, j));
return ++dis[i, j];
}
}