Advertisement
Guest User

Untitled

a guest
Feb 25th, 2017
64
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.94 KB | None | 0 0
  1. /*
  2. the DFS here is basically like DP with memorization. Every cell that has been computed will not be computed again,
  3. only a value look-up is performed. So this is O(mn), m and n being the width and height of the matrix.
  4. To be exact, each cell can be accessed 5 times at most: 4 times from the top, bottom, left and right and one time
  5. from the outermost double for loop. 4 of these 5 visits will be look-ups except for the first one.
  6. So the running time should be lowercase o(5mn), which is of course O(mn).
  7.  
  8.  
  9. To get max length of increasing sequences:
  10.  
  11. 1. Do DFS from every cell
  12. 2. Compare every 4 direction and skip cells that are out of boundary or smaller
  13. 3. Get matrix max from every cell's max (because each cell will have lengths from four directions)
  14. 4. Use matrix[x][y] <= matrix[i][j] so we don't need a visited[m][n] array
  15. 5. The key is to cache the distance because it's highly possible to revisit a cell
  16.  
  17. */
  18. public class Solution {
  19. public int longestIncreasingPath(int[][] matrix) {
  20. if(matrix == null || matrix.length == 0 || matrix[0].length == 0) return 0;
  21. int m = matrix.length, n = matrix[0].length;
  22. int[][] dirs = {{1,0},{-1,0},{0,1},{0,-1}};
  23. int[][] cache = new int[m][n];
  24. int max = 0;
  25. for(int i=0; i<m; i++) {
  26. for(int j=0; j<n; j++) {
  27. int len = dfs(matrix, i, j, cache, dirs);
  28. max = Math.max(max, len);
  29. }
  30. }
  31. return max;
  32. }
  33.  
  34. public int dfs(int[][] matrix, int i, int j, int[][] cache, int[][] dirs) {
  35. if(cache[i][j] != 0) return cache[i][j];
  36. int max = 1;
  37. for(int[] dir : dirs) {
  38. int x = i + dir[0], y = j + dir[1];
  39. if(x < 0 || x >= matrix.length || y < 0 || y >= matrix[0].length || matrix[x][y] <= matrix[i][j]) continue;
  40. int len = 1 + dfs(matrix, x, y, cache, dirs);
  41. max = Math.max(max, len);
  42. }
  43. cache[i][j] = max;
  44. return max;
  45. }
  46. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement