Advertisement
Guest User

Grokking #198

a guest
Nov 21st, 2021
91
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.08 KB | None | 0 0
  1. class Solution {
  2.  
  3.   // Dijkstra
  4.   class NodeValue {
  5.     Integer value; // the current effort to reach from start to current cell
  6.     int row;
  7.     int col;
  8.    
  9.     public NodeValue(int row, int col, Integer value) {
  10.       this.row = row;
  11.       this.col = col;
  12.       this.value = value;
  13.     }
  14.   }
  15.  
  16.   int[][] DIRS = { {-1, 0}, {0, 1}, {1, 0}, {0, -1} };
  17.  
  18.   public int minimumEffortPath(int[][] heights) {
  19.     int rows = heights.length;
  20.     int cols = heights[0].length;
  21.    
  22.     int[][] distance = new int[rows][cols];
  23.     for (int[] row : distance) {
  24.       Arrays.fill(row, Integer.MAX_VALUE);
  25.     }
  26.    
  27.     distance[0][0] = 0;
  28.        
  29.     PriorityQueue<NodeValue> pq = new PriorityQueue<NodeValue>((a,b) -> (a.value.compareTo(b.value)));
  30.     pq.offer(new NodeValue(0, 0, 0));
  31.    
  32.     while (!pq.isEmpty()) {
  33.       NodeValue at = pq.poll();      
  34.       int r = at.row;
  35.       int c = at.col;
  36.      
  37.       // Early stop if met destination
  38.       if (r == rows - 1 && c == cols - 1) {
  39.         return distance[r][c];
  40.       }
  41.      
  42.       // Skip if we have smaller distance value
  43.       if (at.value > distance[r][c]) {
  44.         continue;
  45.       }
  46.      
  47.       for (int i = 0; i < 4; i++) {
  48.         int rr = r + DIRS[i][0];
  49.         int cc = c + DIRS[i][1];
  50.        
  51.         if (0 <= rr && rr < rows && 0 <= cc && cc < cols) {
  52.           // Effort to move from current cell (r, c) to next cell (rr, cc)
  53.           int effort = Math.abs(heights[rr][cc] - heights[r][c]);
  54.  
  55.           // New effort is the max of 2 following values:
  56.           // 1. The effort from the start cell to current cell (r, c)
  57.           // 2. And the effort from current cell (r, c) to next cell (rr, cc)
  58.           int newEffort = Math.max(distance[r][c], effort);
  59.          
  60.           if (newEffort < distance[rr][cc]) {
  61.             // Update current distance if we found less effort path
  62.             distance[rr][cc] = newEffort;
  63.            
  64.             pq.offer(new NodeValue(rr, cc, distance[rr][cc]));
  65.           }
  66.         }
  67.       }
  68.     }
  69.    
  70.     return distance[rows - 1][cols - 1];
  71.   }
  72. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement