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,剪枝。记忆化DFS主要思想:当搜完某一个节点时,保存这个节点后续的信息,当下次再搜到这个节点时,就不用再次搜索了。leetcode 140.Word Break II比这题难,也可以用记忆化DFS方法形成剪枝。
public int longestIncreasingPath(int[][] matrix) { if(matrix==null||matrix.length==0||matrix[0].length==0) return 0; int max=0; int[][] mem=new int[matrix.length][matrix[0].length]; for(int i=0;i<matrix.length;i++){ for(int j=0;j<matrix[0].length;j++){ max=Math.max(max,dfs(matrix,mem,i,j)); } } return max; } public int dfs(int[][] matrix,int[][] mem,int i,int j){ if(mem[i][j]!=0){ return mem[i][j]; } int count=0; if(i+1<matrix.length&&matrix[i+1][j]>matrix[i][j]){ count=Math.max(count,dfs(matrix,mem,i+1,j)); } if(j+1<matrix[0].length&&matrix[i][j+1]>matrix[i][j]){ count=Math.max(count,dfs(matrix,mem,i,j+1)); } if(i-1>=0&&matrix[i-1][j]>matrix[i][j]){ count=Math.max(count,dfs(matrix,mem,i-1,j)); } if(j-1>=0&&matrix[i][j-1]>matrix[i][j]){ count=Math.max(count,dfs(matrix,mem,i,j-1)); } mem[i][j]=count+1; return count+1; }