Skip to content
Related Articles

Related Articles

Improve Article

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

  • Difficulty Level : Hard
  • Last Updated : 12 Jul, 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 7
Explanation: 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.

Below is the implementation of the above approach:

C++14




// C++ implementation of above approach
#include <bits/stdc++.h>
using namespace std;
  
// Function to find K shortest path lengths
void 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 Code
int 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;
}
Output
4 4 7 

Time Complexity: O((N+M)*KlogK)
Auxiliary Space: O(NK)

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students.




My Personal Notes arrow_drop_up
Recommended Articles
Page :