shriyanshi24jindal

Shortest Path in Undirected Graph

Mar 29th, 2026
11
0
Never
Not a member of GistPad yet? Sign Up, it unlocks many cool features!
Java 11.20 KB | None | 0 0
  1. class Pair
  2. {
  3. int first;
  4. int second;
  5. Pair(int first, int second)
  6. {
  7. this.first = first;
  8. this.second = second;
  9. }
  10. }
  11.  
  12. class Solution {
  13. public int[] shortestPath(int V, int[][] edges, int src) {
  14. // Step-1 create a adjancency list
  15. ArrayList<ArrayList<Integer>> adj = new ArrayList<>();
  16. for(int i=0; i<V; i++)
  17. {
  18. adj.add(new ArrayList<>());
  19. }
  20.  
  21. for(int[] edge : edges)
  22. {
  23. int u = edge[0];
  24. int v = edge[1];
  25. adj.get(u).add(v);
  26. adj.get(v).add(u);
  27. }
  28.  
  29. // Step-2 Traverse through nodes starting from source node
  30. Queue<Pair> q = new LinkedList<>();
  31. q.add(new Pair(src, 0));
  32.  
  33. // Step-3 Create a distance matrix which will store shortest distance for each node
  34. int[] distance = new int[V];
  35. Arrays.fill(distance, Integer.MAX_VALUE);
  36. distance[src ] = 0;
  37.  
  38. // Step-4 Traverse through nodes
  39. while(!q.isEmpty())
  40. {
  41. Pair pair = q.poll();
  42. int node = pair.first;
  43. int dist = pair.second;
  44.  
  45. // traverse through neighbour nodes
  46. for(int u : adj.get(node))
  47. {
  48. // if distance of neighbour node is greater than the current distance+1 then update it
  49. if(distance[u] > dist+1)
  50. {
  51. distance[u] = dist+1;
  52. q.add(new Pair(u, dist+1));
  53. }
  54. }
  55. }
  56.  
  57. for(int i=0; i<V; i++)
  58. {
  59. // If a vertex is not reachable from the source, return -1 for that vertex
  60. if(distance[i] == Integer.MAX_VALUE)
  61. distance[i] = -1;
  62. }
  63. return distance;
  64. }
  65. }
RAW Paste Data Copied