Give you an integer matrix (with row size n, column size m),find the longest increasing continuous subsequence in this matrix. (The definition of the longest increasing continuous subsequence here can start at any row or column and go up/down/right/left any direction).
int[] x = { 0,0,1,-1 };int[] y = { 1,-1,0,0 };publicintlongestIncreasingContinuousSubsequenceII(int[][] A) {if (A ==null||A.length==0||A[0].length==0) {return0; }int[][] dp =newint[A.length][A[0].length];int max =0;boolean[][] visited =newboolean[A.length][A[0].length];// do dfs for every location, if the location is already set, skip itfor (int i =0; i <A.length; i++) {for (int j =0; j <A[0].length; j++) { dp[i][j] =dfs(visited, i, j, A, dp); max =Math.max(dp[i][j], max); } }return max;}privateintdfs(boolean[][] visited,int row,int col,int[][] A,int[][] dp) {if (visited[row][col]) {return dp[row][col]; }int ret =1;for (int k =0; k <4; k++) {int ni = row + x[k];int nj = col + y[k];if (inBound(ni, nj, A)&&A[ni][nj] >A[row][col]) { ret =Math.max(ret,dfs(visited, ni, nj, A, dp)+1); } } visited[row][col] =true; dp[row][col] = ret;return ret;}privatebooleaninBound(int i,int j,int[][] A) {if (i <0|| j <0|| i >=A.length|| j >=A[0].length) {returnfalse; }returntrue;}
可以省visited matrix:
int[] x = {0,0,1,-1};int[] y = {1,-1,0,0};publicintlongestIncreasingPath(int[][] matrix) {if (matrix ==null||matrix.length==0|| matrix[0].length==0) {return0; }int n =matrix.length;int m = matrix[0].length;int[][] dp =newint[n][m];int max =0;for (int i =0; i < n; i++) {for (int j =0; j < m; j++) { dp[i][j] =dfs(matrix, i, j, dp); max =Math.max(max, dp[i][j]); } }return max;}privateintdfs(int[][] matrix,int row,int col,int[][] dp) {if (dp[row][col] >0) {return dp[row][col]; }int max =1;for (int k =0; k <4; k++) {int ni = row + x[k];int nj = col + y[k];if (inBound(ni, nj, matrix)&& matrix[ni][nj] > matrix[row][col]) {int ret =dfs(matrix, ni, nj, dp)+1; max =Math.max(ret, max); } } dp[row][col] = max;return dp[row][col]; }privatebooleaninBound(int row,int col,int[][] m) {if (row <0|| col <0|| row >=m.length|| col >= m[0].length) {returnfalse; }returntrue;}