shriyanshi24jindal

Shortest Distance in a Binary Maze

Mar 29th, 2026
10
0
Never
Not a member of GistPad yet? Sign Up, it unlocks many cool features!
Java 14.74 KB | None | 0 0
  1. // User function Template for Java
  2. class Pair
  3. {
  4. int row;
  5. int col;
  6. int dist;
  7. Pair(int dist, int row, int col)
  8. {
  9. this.dist = dist;
  10. this.row = row;
  11. this.col = col;
  12. }
  13. }
  14.  
  15. class Solution {
  16.  
  17. int shortestPath(int[][] grid, int[] source, int[] destination) {
  18. // same starting and ending position
  19. if(source[0] == destination[0] && source[1] == destination[1])
  20. return 0;
  21.  
  22. int n=grid.length, m=grid[0].length;
  23.  
  24. // Step-1 Create a distance matrix
  25. int[][] distance = new int[n][m];
  26. for(int i=0;i<n;i++)
  27. {
  28. for(int j=0;j<m;j++)
  29. {
  30. distance[i][j]=(int)1e9;
  31. }
  32. }
  33. distance[source[0]][source[1]] = 0;
  34.  
  35. // Step-2 Store the nodes into MIN-HEAP accoriding to node's distances
  36. PriorityQueue<Pair> pq = new PriorityQueue<>( (x,y) -> Integer.compare(x.dist, y.dist));
  37. pq.add(new Pair(0, source[0], source[1]));
  38.  
  39. int[] deltaRow = {-1, 0, 1, 0};
  40. int[] deltaCol = {0, 1, 0, -1};
  41.  
  42. // Step-3 Traverse all nodes and edges
  43. while(!pq.isEmpty())
  44. {
  45. Pair pair = pq.poll();
  46. int row = pair.row;
  47. int col = pair.col;
  48. int currentDist = pair.dist;
  49.  
  50. // traversing in all 4-directions
  51. for(int i=0; i<4; i++)
  52. {
  53. int nRow = row + deltaRow[i];
  54. int nCol = col + deltaCol[i];
  55.  
  56. if(nRow >=0 && nRow < n && nCol >=0 && nCol < m)
  57. {
  58. // only traverse through neighbour if it's cell value is 1
  59. if(grid[nRow][nCol] == 1)
  60. {
  61. // if we found destination node
  62. if(nRow == destination[0] && nCol == destination[1])
  63. return currentDist+1;
  64.  
  65. // checking if new distance is less than the current distance stored
  66. // if yes then update it and add pair to queue
  67. if(distance[nRow][nCol] > currentDist + 1)
  68. {
  69. distance[nRow][nCol] = currentDist + 1;
  70. pq.add(new Pair(currentDist+1, nRow, nCol));
  71. }
  72. }
  73. }
  74. }
  75. }
  76. return -1;
  77. }
  78. }
RAW Paste Data Copied