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 };
public int longestIncreasingContinuousSubsequenceII(int[][] A) {
if (A == null || A.length == 0 || A[0].length == 0) {
return 0;
}
int[][] dp = new int[A.length][A[0].length];
int max = 0;
boolean[][] visited = new boolean[A.length][A[0].length];
// do dfs for every location, if the location is already set, skip it
for (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;
}
private int dfs(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;
}
private boolean inBound(int i, int j, int[][] A) {
if (i < 0 || j < 0 || i >= A.length || j >= A[0].length) {
return false;
}
return true;
}
可以省visited matrix:
int[] x = {0, 0, 1, -1};
int[] y = {1, -1, 0, 0};
public int longestIncreasingPath(int[][] matrix) {
if (matrix == null || matrix.length == 0 || matrix[0].length == 0) {
return 0;
}
int n = matrix.length;
int m = matrix[0].length;
int[][] dp = new int[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;
}
private int dfs(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];
}
private boolean inBound(int row, int col, int[][] m) {
if (row < 0 || col < 0 || row >= m.length || col >= m[0].length) {
return false;
}
return true;
}