Skip to content

Commit e4c5366

Browse files
committed
add: shortestPath
1 parent c8d8179 commit e4c5366

File tree

1 file changed

+59
-0
lines changed

1 file changed

+59
-0
lines changed

java/Graphs/ShortestPath.java

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
import java.util.ArrayList;
2+
import java.util.Arrays;
3+
import java.util.HashMap;
4+
import java.util.List;
5+
import java.util.Map;
6+
import java.util.PriorityQueue;
7+
8+
public class ShortestPath {
9+
public int[] shortestPath(int n, int[][] edges, int start) {
10+
Map<Integer, List<int[]>> graph = new HashMap<>();
11+
int[] distances = new int[n];
12+
Arrays.fill(distances, Integer.MAX_VALUE);
13+
distances[start] = 0;
14+
// Represent the graph as an adjacency list.
15+
for (int[] edge : edges) {
16+
int u = edge[0];
17+
int v = edge[1];
18+
int w = edge[2];
19+
20+
graph.putIfAbsent(u, new ArrayList<>());
21+
graph.putIfAbsent(v, new ArrayList<>());
22+
graph.get(u).add(new int[]{v, w});
23+
graph.get(v).add(new int[]{u, w});
24+
}
25+
PriorityQueue<int[]> minHeap = new PriorityQueue<>((a, b) -> Integer.compare(a[0], b[0]));
26+
minHeap.offer(new int[]{0, start}); // (distance, node)
27+
// Use Dijkstra's algorithm to find the shortest path between the start node
28+
// and all other nodes.
29+
while (!minHeap.isEmpty()) {
30+
int[] curr = minHeap.poll();
31+
int currDist = curr[0];
32+
int currNode = curr[1];
33+
// If the current distance to this node is greater than the recorded
34+
// distance, we've already found the shortest distance to this node.
35+
if (currDist > distances[currNode]) {
36+
continue;
37+
}
38+
// Update the distances of the neighboring nodes.
39+
for (int[] edge : graph.get(currNode)) {
40+
int neighbor = edge[0];
41+
int weight = edge[1];
42+
int neighborDist = currDist + weight;
43+
// Only update the distance if we find a shorter path to this
44+
// neighbor.
45+
if (neighborDist < distances[neighbor]) {
46+
distances[neighbor] = neighborDist;
47+
minHeap.offer(new int[]{neighborDist, neighbor});
48+
}
49+
}
50+
}
51+
// Convert all infinity values to -1, representing unreachable nodes.
52+
for (int i = 0; i < n; i++) {
53+
if (distances[i] == Integer.MAX_VALUE) {
54+
distances[i] = -1;
55+
}
56+
}
57+
return distances;
58+
}
59+
}

0 commit comments

Comments
 (0)