(int n, int source, int destination)
| 51 | |
| 52 | // Dijkstra's algorithm to find the shortest path from source to destination |
| 53 | private int runDijkstra(int n, int source, int destination) { |
| 54 | int[] minDistance = new int[n]; |
| 55 | boolean[] visited = new boolean[n]; |
| 56 | // sort in increasing order of edge weight |
| 57 | // [u,w] (node, weight to node) |
| 58 | PriorityQueue<int[]> queue = new PriorityQueue<>(new Comparator<int[]>(){ |
| 59 | public int compare(int a[], int b[]){ |
| 60 | return a[1] - b[1]; |
| 61 | } |
| 62 | }); |
| 63 | |
| 64 | Arrays.fill(minDistance, INF); |
| 65 | minDistance[source] = 0; |
| 66 | queue.add(new int[] { source, 0 }); |
| 67 | |
| 68 | while (!queue.isEmpty()) { |
| 69 | int[] curr = queue.poll(); |
| 70 | int u = curr[0]; |
| 71 | int d = curr[1]; |
| 72 | |
| 73 | if (d > minDistance[u]) continue; |
| 74 | |
| 75 | for (int[] neighbour : graph[u]) { |
| 76 | int v = neighbour[0]; |
| 77 | int weight = neighbour[1]; |
| 78 | |
| 79 | if (d + weight < minDistance[v]) { |
| 80 | minDistance[v] = d + weight; |
| 81 | queue.add(new int[] { v, minDistance[v] }); |
| 82 | } |
| 83 | } |
| 84 | } |
| 85 | |
| 86 | return minDistance[destination]; |
| 87 | } |
| 88 | } |
no test coverage detected