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]
Note:
- Use
matrix[x][y] > matrix[i][j]
so we don't need avisited[m][n]
array - The key is to
cache
the distance because it's highly possible to revisit a cell
Follow Up: How to get the actual longest increasing path
我的想法:类似Largest Divisible Subset, 除了一个dp[i][j]记录longest length以外,另外再用一个matrix pre[i][j]记录(i,j)longest increasing path上一跳位置, 并用一个variable记录最后最长的path的起始位置(第19行每次res更新时更新)。最后通过这个起始位置沿着一个一个上一跳位置,可以求出path
1 public class Solution { 2 int[][] dp; 3 int[][] directions = new int[][]{{-1,0},{1,0},{0,-1},{0,1}}; 4 int m; 5 int n; 6 7 public int longestIncreasingPath(int[][] matrix) { 8 if (matrix==null || matrix.length==0 || matrix[0].length==0) return 0; 9 m = matrix.length; 10 n = matrix[0].length; 11 dp = new int[m][n]; 12 13 int result = 0; 14 15 for (int i=0; i<m; i++) { 16 for (int j=0; j<n; j++) { 17 if (dp[i][j] == 0) 18 dp[i][j] = DFS(i, j, matrix); 19 result = Math.max(result, dp[i][j]); 20 } 21 } 22 return result; 23 } 24 25 public int DFS(int i, int j, int[][] matrix) { 26 if (dp[i][j] != 0) return dp[i][j]; 27 dp[i][j] = 1; 28 for (int[] dir : directions) { 29 int x = i + dir[0]; 30 int y = j + dir[1]; 31 if (x<0 || y<0 || x>=m || y>=n || matrix[x][y]<=matrix[i][j]) continue; 32 dp[i][j] = Math.max(dp[i][j], DFS(x, y, matrix)+1); 33 } 34 return dp[i][j]; 35 } 36 }