Code Logo

Shortest Path in Weighted Graph

Published at05 Jan 2026
Hard 23 views
Like3

You are given a weighted graph with n nodes, a list of edges [u, v, w], and two nodes called source and destination. You need the minimum total weight needed to travel from the source to the destination.

Some routes may use fewer edges but still cost more, so counting hops is not enough. You have to compare the total sum of edge weights along each possible route.

For example, with edges = [[0,1,2],[0,2,4],[1,3,1],[2,3,3],[3,4,5]], the cheapest way from 0 to 4 is 0 -> 1 -> 3 -> 4, which costs 8. If the destination cannot be reached at all, return -1.

So the task is to find the minimum path cost between two nodes in a weighted graph, or report that no path exists.

Example Input & Output

Example 1
Input
n = 5, edges = [[0,1,2], [0,2,4], [1,3,1], [2,3,3], [3,4,5]], source = 0, destination = 4
Output
8
Explanation

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.

Example 2
Input
n = 2, edges = [], source = 0, destination = 1
Output
-1
Explanation

Since there are no edges in the graph, no path exists between nodes 0 and 1, so the function returns -1.

Example 3
Input
n = 3, edges = [[0,1,1], [1,2,2]], source = 0, destination = 2
Output
3
Explanation

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

Recommendation Algorithm Flow for Shortest Path in Weighted Graph
Recommendation Algorithm Flow for Shortest Path in Weighted Graph

Solution Approach

The standard solution is Dijkstra's algorithm.

First build an adjacency list so you can quickly see which neighbors each node connects to and what each move costs. Then keep a distance array where dist[x] is the best cost found so far for node x.

Use a min-heap priority queue starting from source with distance 0. Each time you pop the node with the smallest current distance, try relaxing all of its outgoing edges. If going through that node gives a neighbor a smaller distance, update it and push the new value into the heap.

When destination is popped, its distance is the shortest possible. If it is never reached, return -1. This runs in about O((n + m) log n) time for m edges.

Best Answers

java

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;
    }
}