Skip to content

Instantly share code, notes, and snippets.

@Rabierre
Last active May 24, 2019 07:49
Show Gist options
  • Save Rabierre/8b093ef10982079f745d44b87754044b to your computer and use it in GitHub Desktop.
Save Rabierre/8b093ef10982079f745d44b87754044b to your computer and use it in GitHub Desktop.
class Solution {
public int longestIncreasingPath(int[][] matrix) {
if (matrix.length == 0) return 0;
int rowN = matrix.length, colN = matrix[0].length;
int res = 0;
int[][] cache = new int[rowN][colN];
for (int i=0; i<rowN; i++) {
for (int j=0; j<colN; j++) {
res = Math.max(res, findMax(matrix, i, j, cache)+1);
}
}
return res;
}
int findMax(int[][] A, int i, int j, int[][] cache) {
if (cache[i][j] != 0) return cache[i][j];
int rowN = A.length, colN = A[0].length;
if (i>0 && i < rowN && A[i][j] < A[i-1][j]) // top
cache[i][j] = findMax(A, i-1, j, cache)+1;
if (i < rowN-1 && A[i][j] < A[i+1][j]) // bottom
cache[i][j] = Math.max(cache[i][j], findMax(A, i+1, j, cache)+1);
if (j>0 && j < colN && A[i][j] < A[i][j-1]) // left
cache[i][j] = Math.max(cache[i][j], findMax(A, i, j-1, cache)+1);
if (j < colN-1 && A[i][j] < A[i][j+1]) // right
cache[i][j] = Math.max(cache[i][j], findMax(A, i, j+1, cache)+1);
return cache[i][j];
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment