1st to Kth shortest path lengths from node 1 to N in given Graph - GeeksforGeeks

28 Oct, 2021
Given a directed and weighted graph of N nodes and M edges, the task is to find the 1st to Kth shortest path lengths from node 1 to N.
Examples:
Input: N = 4, M = 6, K = 3, edges = {{1, 2, 1}, {1, 3, 3}, {2, 3, 2}, {2, 4, 6}, {3, 2, 8}, {3, 4, 1}}Output: 4 4 7Explanation: The shortest path length from 1 to N is 4, 2nd shortest length is also 4 and 3rd shortest length is 7.
Input: N = 3, M = 3, K = 2, edges = {{1, 2, 2}, {2, 3, 2}, {1, 3, 1}}Output: 1 4
Approach: The idea is to traverse all vertices of the graph using BFS and use priority queue to store the vertices for which the shortest distance is not finalized yet, and also to get the minimum distance vertex. Follow the steps below for the approach. 
Initialize a priority queue, say, pq of size N to store the vertex number and distance value.
Initialize a 2-d vector, say, dis of size N*K and initialize all values with a very large number, say, 1e9.
Set dis[1][0] to zero, the distance value of the source vertex.
Iterate while pq is not empty.Pop the value from pq, and store the vertex value in variable u and vertex distance in variable d.If d is greater than the distance u, then continue.For every adjacent vertex v of u check if the Kth distance value is more than the weight of u-v plus the distance value of u, then update the Kth distance value of v and sort the k distances of vertex v.
Pop the value from pq, and store the vertex value in variable u and vertex distance in variable d.
If d is greater than the distance u, then continue.
For every adjacent vertex v of u check if the Kth distance value is more than the weight of u-v plus the distance value of u, then update the Kth distance value of v and sort the k distances of vertex v.
Below is the implementation of the above approach:
C++14
Javascript
// C++ implementation of above approach#include <bits/stdc++.h>using namespace std; // Function to find K shortest path lengthsvoid findKShortest(int edges[][3], int n, int m, int k){     // Initialize graph    vector<vector<pair<int, int> > > g(n + 1);    for (int i = 0; i < m; i++) {        // Storing edges        g[edges[i][0]].push_back({ edges[i][1], edges[i][2] });    }     // Vector to store distances    vector<vector<int> > dis(n + 1, vector<int>(k, 1e9));     // Initialization of priority queue    priority_queue<pair<int, int>,                   vector<pair<int, int> >,                   greater<pair<int, int> > >        pq;    pq.push({ 0, 1 });    dis[1][0] = 0;     // while pq has elements    while (!pq.empty()) {        // Storing the node value        int u = pq.top().second;         // Storing the distance value        int d = (pq.top().first);        pq.pop();        if (dis[u][k - 1] < d)            continue;        vector<pair<int, int> > v = g[u];         // Traversing the adjacency list        for (int i = 0; i < v.size(); i++) {            int dest = v[i].first;            int cost = v[i].second;             // Checking for the cost            if (d + cost < dis[dest][k - 1]) {                dis[dest][k - 1] = d + cost;                 // Sorting the distances                sort(dis[dest].begin(), dis[dest].end());                 // Pushing elements to priority queue                pq.push({ (d + cost), dest });            }        }    }     // Printing K shortest paths    for (int i = 0; i < k; i++) {        cout << dis[n][i] << " ";    }} // Driver Codeint main(){     // Given Input    int N = 4, M = 6, K = 3;    int edges[][3] = { { 1, 2, 1 }, { 1, 3, 3 },                       { 2, 3, 2 }, { 2, 4, 6 },                       { 3, 2, 8 }, { 3, 4, 1 } };     // Function Call    findKShortest(edges, N, M, K);     return 0;}
<script> // Javascript implementation of above approach // Function to find K shortest path lengthsfunction findKShortest(edges, n, m, k){     // Initialize graph    var g = Array.from(Array(n + 1), ()=>new Array());    for (var i = 0; i < m; i++)    {             // Storing edges        g[edges[i][0]].push([edges[i][1], edges[i][2]]);    }     // Vector to store distances    var dis = Array.from(Array(n+1), ()=> Array(k).fill(1000000000));     // Initialization of priority queue    var pq = [];    pq.push([0, 1]);    dis[1][0] = 0;     // while pq has elements    while (pq.length != 0)    {             // Storing the node value        var u = pq[pq.length-1][1];         // Storing the distance value        var d = (pq[pq.length-1][0]);        pq.pop();        if (dis[u][k - 1] < d)            continue;        var v = g[u];         // Traversing the adjacency list        for (var i = 0; i < v.length; i++) {            var dest = v[i][0];            var cost = v[i][1];             // Checking for the cost            if (d + cost < dis[dest][k - 1]) {                dis[dest][k - 1] = d + cost;                 // Sorting the distances                dis[dest].sort((a,b)=>a-b);                 // Pushing elements to priority queue                pq.push([(d + cost), dest ]);                pq.sort();            }        }    }     // Printing K shortest paths    for (var i = 0; i < k; i++) {        document.write(dis[n][i] + " ");    }} // Driver Code // Given Inputvar N = 4, M = 6, K = 3;var edges = [ [ 1, 2, 1 ], [ 1, 3, 3 ],                   [ 2, 3, 2 ], [ 2, 4, 6 ],                   [ 3, 2, 8 ], [ 3, 4, 1 ] ];                    // Function CallfindKShortest(edges, N, M, K); // This code is contributed by rrrtnx.</script>
4 4 7 
Time Complexity: O((N+M)*KlogK)Auxiliary Space: O(NK)
rrrtnx
BFS
priority-queue
Shortest Path
Graph
Sorting
Sorting
Graph
Shortest Path
BFS
priority-queue
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Vertex Cover Problem | Set 1 (Introduction and Approximate Algorithm)
Graph Coloring | Set 2 (Greedy Algorithm)
Best First Search (Informed Search)
Find if there is a path between two vertices in a directed graph
Shortest Path in a weighted Graph where weight of an edge is 1 or 2