您的位置:首页 > 其它

Leetcode: Longest Increasing Path in a Matrix

2016-01-25 10:42 393 查看
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.


DFS + DP:

use a two dimensional matrix dp[i][j] to store the length of the longest increasing path starting at matrix[i][j]

transferring function is: dp[i][j] = max(dp[i][j], dp[x][y] + 1), where dp[x][y] is its neighbor with matrix[x][y] > matrix[i][j]

public class Solution {
int[][] dp;
int[][] directions = new int[][]{{-1,0},{1,0},{0,-1},{0,1}};
int m;
int n;
int[][] mx;
public int longestIncreasingPath(int[][] matrix) {
if (matrix==null || matrix.length==0 || matrix[0].length==0) return 0;
m = matrix.length;
n = matrix[0].length;
dp = new int[m]
;
mx = matrix;
int result = 0;
for (int i=0; i<m; i++) {
for (int j=0; j<n; j++) {
dp[i][j] = Integer.MIN_VALUE;
}
}
for (int i=0; i<m; i++) {
for (int j=0; j<n; j++) {
result = Math.max(result, DFS(i,j));
}
}
return result;
}

public int DFS(int i, int j) {
if (dp[i][j] != Integer.MIN_VALUE) return dp[i][j];
dp[i][j] = 1;
for (int[] dir : directions) {
int x = i + dir[0];
int y = j + dir[1];
if (x<0 || y<0 || x>=m || y>=n || mx[x][y]<=mx[i][j]) continue;
dp[i][j] = Math.max(dp[i][j], DFS(x,y)+1);
}
return dp[i][j];
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: