您的位置:首页 > 其它

[leetcode]329. Longest Increasing Path in a Matrix

2017-08-24 15:17 381 查看
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]
.

我们需要找到一个数组中的最长递增路径,这条路径可以往上下左右延伸,但是不能超出边界。

看到这一题首先可以想到深度优先搜索。要想求得最长递增路径,只需把从每一个结点开始的最长递增序列求得,然后取最大值即可。但这里的深度优先搜索寻找下一个结点的条件是必须保证下一个结点的val大于当前结点,我们可以用递归来实现。另外,我们发现并不是每个结点都能作为一条最长递增路径的首结点:当某个结点p周围有比它小的结点w存在时,p一定不能作为最长递增路径的首结点,因为把w加到p之前,我们得到一条更长的递增路径。

接下来就是实现了,我们可以用一个depth[i][j]数组保存以结点nums[i, j]为首结点的最长递增路径的长度,这样就避免了重复计算。

class Solution {
public int longestIncreasingPath(int[][] matrix) {
if(matrix.length == 0)
return 0;
int max = Integer.MIN_VALUE;

int[][] depth = new int[matrix.length][matrix[0].length];
for(int i = 0; i < matrix.length; i++){
for(int j = 0; j < matrix[0].length; j++){
depth[i][j] = -1;
}
}

for(int i = 0; i < matrix.length; i++){
for(int j = 0; j < matrix[0].length; j++){
if(!hasSmaller(i, j, matrix)){
int deep = (depth[i][j] == -1 ? depthSearch(i, j, matrix, depth) : depth[i][j]);
max = deep > max ? deep : max;
}
}
}
return max;
}

public boolean hasSmaller(int i, int j, int[][] matrix){
if(i != 0 && matrix[i][j] > matrix[i-1][j])
return true;
if(i != matrix.length-1 && matrix[i][j] > matrix[i+1][j])
return true;
if(j != 0 && matrix[i][j] > matrix[i][j-1])
return true;
if(j != matrix[0].length-1 && matrix[i][j] > matrix[i][j+1])
return true;

return false;
}

public int depthSearch(int i, int j, int[][] matrix, int[][] depth){
int max = Integer.MIN_VALUE;
if(i != 0 && matrix[i][j] < matrix[i-1][j]){
int temp = (depth[i-1][j] == -1 ? depthSearch(i-1, j, matrix, depth) : depth[i-1][j]) + 1;
max = temp > max ? temp : max;
}
if(i != matrix.length-1 && matrix[i][j] < matrix[i+1][j]){
int temp = (depth[i+1][j] == -1 ? depthSearch(i+1, j, matrix, depth) : depth[i+1][j]) + 1;
max = temp > max ? temp : max;
}
if(j != 0 && matrix[i][j] < matrix[i][j-1]){
int temp = (depth[i][j-1] == -1 ? depthSearch(i, j-1, matrix, depth) : depth[i][j-1]) + 1;
max = temp > max ? temp : max;
}
if(j != matrix[0].length-1 && matrix[i][j] < matrix[i][j+1]){
int temp = (depth[i][j+1] == -1 ? depthSearch(i, j+1, matrix, depth) : depth[i][j+1]) + 1;
max = temp > max ? temp : max;
}
depth[i][j] = (max == Integer.MIN_VALUE ? 1 : max);
return depth[i][j];
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode 动态规划