Shortest Path in Weighted Graph
Shortest Path in Weighted Graph is about finding the cheapest route, not the route with the fewest hops. You are given n nodes, weighted undirected edges, a source, and a destination. Return the minimum total weight from source to destination, or -1 if no route exists.
Because edge weights are positive, Dijkstra with a min-heap is the right move. Start with distance 0 at source, always pop the node with the smallest known distance, then relax its neighbors. If going through the current node gives a cheaper distance, update it and push the new state into the heap.
There are two easy-to-miss details. First, build adjacency in both directions since the graph is undirected. Second, skip stale heap entries when their cost is already worse than the best saved distance for that node. That keeps the run efficient and avoids extra reprocessing.
The judge includes disconnected graphs, direct-but-expensive edges versus longer-but-cheaper paths, and empty-edge cases. So keep it simple: one integer output only, with strict relax logic and clean distance tracking. Quick intuition: think like GPS, always expand the currently cheapest checkpoint first.
Also keep in mind that a node may enter the heap multiple times with different costs. That is normal. You only trust the smallest valid one, and ignore the rest. This small rule is what keeps answers correct and performance stable on dense inputs.
Examples
The shortest path is 0 -> 1 -> 3 -> 4, with edge weights 2 + 1 + 5 = 8, which is the minimum total weight to reach node 4 from node 0.
Since there are no edges in the graph, no path exists between nodes 0 and 1, so the function returns -1.
The shortest path is 0 -> 1 -> 2, with edge weights 1 + 2 = 3, representing the minimum total weight to reach node 2 from node 0.
Algorithm Flow

Best Answers
class Solution {
public int shortest_path(Object nObj, Object edgesObj, Object srcObj, Object dstObj) {
int n = (int) nObj;
int source = (int) srcObj;
int destination = (int) dstObj;
int[][] edges = (int[][]) edgesObj;
java.util.List<java.util.List<int[]>> adj = new java.util.ArrayList<>();
for(int i=0; i<n; i++) adj.add(new java.util.ArrayList<>());
for(int[] edge : edges) {
adj.get(edge[0]).add(new int[]{edge[1], edge[2]});
adj.get(edge[1]).add(new int[]{edge[0], edge[2]});
}
int[] dist = new int[n];
java.util.Arrays.fill(dist, Integer.MAX_VALUE);
dist[source] = 0;
java.util.PriorityQueue<int[]> pq = new java.util.PriorityQueue<>((a, b) -> a[0] - b[0]);
pq.offer(new int[]{0, source});
while(!pq.isEmpty()) {
int[] curr = pq.poll();
int d = curr[0];
int u = curr[1];
if(u == destination) return d;
if(d > dist[u]) continue;
for(int[] neighbor : adj.get(u)) {
int v = neighbor[0];
int w = neighbor[1];
if(dist[u] + w < dist[v]) {
dist[v] = dist[u] + w;
pq.offer(new int[]{dist[v], v});
}
}
}
return -1;
}
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this problem.
