Advertisement
ogv

Untitled

ogv
Feb 7th, 2020
111
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.33 KB | None | 0 0
  1. class Solution {
  2. private int[][] dirs = new int[][] {{-1, 0}, {0, -1}, {1, 0}, {0, 1}};
  3.  
  4. public int longestIncreasingPath(int[][] matrix) {
  5. if (matrix.length == 0) return 0;
  6.  
  7. int max = 0;
  8.  
  9. Queue<int[]> q = new ArrayDeque<>();
  10.  
  11. for (int r = 0; r < matrix.length; r++)
  12. for (int c = 0; c < matrix[0].length; c++) {
  13. if (next(r, c, matrix).size() == 0) q.add(new int[] {r, c, 1});
  14. }
  15.  
  16. while (!q.isEmpty()) {
  17. int[] item = q.poll();
  18. max = Math.max(max, item[2]);
  19. for (int[] n: next(item[0], item[1], matrix)) q.add(new int[] { n[0], n[1], item[2]});
  20. }
  21.  
  22. return max;
  23. }
  24.  
  25. private List<int[][]> next(int r, int c, int[][] matrix) {
  26. ArrayList<int[][]> result = new ArrayList<>();
  27.  
  28. for (int[] dir: dirs) {
  29. int nr = r + dir[0];
  30. int nc = c + dir[1];
  31.  
  32. if (nr == r && nc == c) continue;
  33. if (nr < 0 || nr >= matrix.length) continue;
  34. if (nc < 0 || nc >= matrix[0].length ) continue;
  35. if (matrix[nr][nc] <= matrix[r][c]) continue;
  36.  
  37. result.add(new int[] { nr, nc });
  38. }
  39.  
  40. return result;
  41. }
  42. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement