1. class Pair
  2. {
  3. int row;
  4. int col;
  5. int dist;
  6. Pair(int dist, int row, int col)
  7. {
  8. this.dist = dist;
  9. this.row = row;
  10. this.col = col;
  11. }
  12. }
  13.  
  14. class Solution {
  15. // IDEA: Dijkstra alogrithm, instead of storeing distance as 0 for source vertex, store the water elevation
  16. public int swimInWater(int[][] grid) {
  17. int n = grid.length;
  18. int m = grid[0].length;
  19.  
  20. int[] source = new int[]{0,0};
  21. int[] destination = new int[]{n-1,m-1};
  22.  
  23. // same starting and ending position
  24. if(source[0] == destination[0] && source[1] == destination[1])
  25. return 0;
  26.  
  27. // Step-1 Create a distance matrix
  28. int[][] distance = new int[n][m];
  29. for(int i=0;i<n;i++)
  30. {
  31. for(int j=0;j<m;j++)
  32. {
  33. distance[i][j]=Integer.MAX_VALUE;
  34. }
  35. }
  36. // Starting point elevation matters!
  37. distance[source[0]][source[1]] = grid[0][0];
  38.  
  39. // Step-2 Store the nodes into MIN-HEAP accoriding to node's distances
  40. PriorityQueue<Pair> pq = new PriorityQueue<>( (x,y) -> Integer.compare(x.dist, y.dist));
  41. // Starting point elevation matters!
  42. pq.add(new Pair(grid[0][0], source[0], source[1]));
  43.  
  44.  
  45. int[] deltaRow = {-1, 0, 1, 0};
  46. int[] deltaCol = {0, 1, 0, -1};
  47.  
  48. int maxNode = 0;
  49. while(!pq.isEmpty())
  50. {
  51. Pair pair = pq.poll();
  52. int row = pair.row;
  53. int col = pair.col;
  54. int currentDist = pair.dist;
  55.  
  56. for(int i=0; i<4; i++)
  57. {
  58. int nRow = row + deltaRow[i];
  59. int nCol = col + deltaCol[i];
  60.  
  61. if(nRow >= 0 && nRow < n && nCol>=0 && nCol < m)
  62. {
  63. // In the “Swim in Rising Water”, the cost to enter a cell is the elevation of the cell.
  64. int nextDist = Math.max(currentDist, grid[nRow][nCol]);
  65.  
  66. // checking if new distance is less than the current distance stored
  67. // if yes then update it and add pair to queue
  68. if(distance[nRow][nCol] > nextDist)
  69. {
  70. distance[nRow][nCol] = nextDist;
  71. pq.add(new Pair(nextDist, nRow, nCol));
  72. }
  73. }
  74. }
  75. }
  76. return distance[n-1][m-1];
  77. }
  78. }