Shortest Path with Exactly k Edges in a Directed and Weighted Graph

In a coordinated and weighted chart, the issue of finding the most brief way with precisely k edges includes deciding the way that has the least weight while navigating precisely k edges. This will be accomplished by employing dynamic programming strategies, such as employing a 3D framework to store the least weight of all conceivable ways. The calculation repeats over the vertices and edges, overhauling the least weight at each step. By considering all conceivable ways with precisely k edges, the calculation distinguishes the most limited way with k edges within the chart.

Methods Used

  • Naive Recursive approach

  • Dijkstra's Algorithm with Edge Constraints

Naive Recursive approach

The Naive Recursive approach could be an essential and clear strategy for problem−solving that includes breaking down a complex issue into smaller subproblems and tackling them recursively. In this approach, a work calls itself more than once to fathom subproblems until a base case is reached. Be that as it may, it can be wasteful for bigger issue occurrences due to repetitive computations and covering subproblems. It needs optimization methods like memoization or energetic programming. The Gullible Recursive approach is simple to get and actualize but may endure exponential time complexity. It is ordinarily utilised for small−scale issues or as a beginning point for more optimised calculations.


  • Characterise a work shortest path (graph, u, v, k) that takes the chart, source vertex u, goal vertex v, and the number of edges k as input.

  • Check for base cases:

  • a. On the off chance that k is and u is breaking even with v, return (since no edges are permitted in this case).

  • The second. If k is 1 and there is an edge between u and v in the chart, return its weight.

  • c. On the off chance that k is less than or breaks even with 0, return boundlessness (since negative or zero edges are not allowed).

  • Initialise a variable res with interminability to store the shortest path distance.

  • The graph should be iterated through all vertices as follows:

  • a. In the event that u and i do not rise to u or v, there is an edge from u to i:

  • Recursively call shortestPath with i as the modern source vertex, v as the goal vertex, and k−1 as the number of edges remaining.

  • If the returned result isn't limitless, upgrade res to the least of res and the entirety of the weight of the current edge and the recursive result.

  • Return the value of res as the most limited way to separate with precisely k edges.


#include <iostream>
#include <climits>

#define V 4
#define INF INT_MAX

int shortestPathWithKEdges(int graph[][V], int source, int destination, int k) {
    // Base cases
    if (k == 0 && source == destination)
        return 0;
    if (k == 1 && graph[source][destination] != INF)
        return graph[source][destination];
    if (k <= 0)
        return INF;

    // Initialize result
    int shortestPathDistance = INF;

    // Explore all adjacent vertices of the source vertex
    for (int i = 0; i < V; i++) {
        if (graph[source][i] != INF && source != i && destination != i) {
            int recursiveDistance = shortestPathWithKEdges(graph, i, destination, k - 1);
            if (recursiveDistance != INF)
                shortestPathDistance = std::min(shortestPathDistance, graph[source][i] + recursiveDistance);

    return shortestPathDistance;

int main() {
    int graph[V][V] = {
        {0, 10, 3, 2},
        {INF, 0, INF, 7},
        {INF, INF, 0, 6},
        {INF, INF, INF, 0}
    int source = 0, destination = 3, k = 2;
    std::cout << "Weight of the shortest path is " << shortestPathWithKEdges(graph, source, destination, k) << std::endl;
    return 0;


Weight of the shortest path is 9

Dijkstra's Algorithm with Edge Constraints

Dijkstra's Algorithm with Edge Limitations is a chart traversal calculation that identifies the shortest path between a source vertex and all other vertices on a chart. It takes into consideration the limitations or restrictions on the edges of the chart, such as the most extreme or least extreme edge weights. The calculation keeps up a needed line of vertices and iteratively chooses the vertex with the least removal. At that point, it unwinds the neighbouring vertices by upgrading their separations on the off chance that a shorter way is found. This preparation proceeds until all vertices have been visited. Dijkstra's Algorithm with Edge Imperatives guarantees that the way chosen fulfils the desired edge limitations, whereas finding the most limited way


  • Make a work by Dijkstra with the following parameters

  • Graph: the input chart with vertices and edges

    Source: the beginning vertex for the most limited path

    Constraints: the limitations or impediments on the edges

    Initialise a purge set of gone−by vertices and a need line to store the vertices and their distances.

  • Create a remove cluster and set the remove of all vertices to interminability except for the source vertex, which is set to 0.

  • Enqueue the source vertex into the needed line with its distance.

  • While the need line isn't purgeable, do the following:

  • Dequeue the vertex with the least elimination from the want queue.

  • If the vertex has now no longer been visited,

  • Mark it as visited.

  • For every neighbouring vertex of the modern vertex:

  • Apply the brink obstacles to determine if the brink may be considered.

  • Calculate the unused distance from the supply vertex to the neighbouring vertex, thinking about the brink weight and constraints.

  • If the present day separate is shorter than the modern separate, improve the separate array.

  • Enqueue the neighbouring vertex into the wanted line with its unused distance.

  • After going to all vertices, the separate cluster will comprise the maximum short separations from the supply vertex to every vertex pleasing the brink constraints.

  • Return the separate cluster as the result.


#include <iostream>
#include <vector>
#include <limits>

struct Edge {
    int destination;
    int weight;

void dijkstra(const std::vector<std::vector<Edge>>& graph, int source, std::vector<int>& distance) {
    int numVertices = graph.size();
    std::vector<bool> visited(numVertices, false);
    distance.resize(numVertices, std::numeric_limits<int>::max());
    distance[source] = 0;

    for (int i = 0; i < numVertices - 1; ++i) {
        int minDistance = std::numeric_limits<int>::max();
        int minVertex = -1;

        for (int v = 0; v < numVertices; ++v) {
            if (!visited[v] && distance[v] < minDistance) {
                minDistance = distance[v];
                minVertex = v;

        if (minVertex == -1)

        visited[minVertex] = true;

        for (const auto& edge : graph[minVertex]) {
            int destination = edge.destination;
            int weight = edge.weight;

            if (!visited[destination] && distance[minVertex] != std::numeric_limits<int>::max() &&
                distance[minVertex] + weight < distance[destination]) {
                distance[destination] = distance[minVertex] + weight;

int main() {
    int numVertices = 4;
    int source = 0;
    std::vector<std::vector<Edge>> graph(numVertices);

    // Add edges to the graph (destination, weight)
    graph[0] = {{1, 10}, {2, 3}};
    graph[1] = {{2, 1}, {3, 7}};
    graph[2] = {{3, 6}};

    std::vector<int> distance;
    dijkstra(graph, source, distance);

    // Print the shortest distances from the source vertex
    std::cout << "Shortest distances from vertex " << source << ":\n";
    for (int i = 0; i < numVertices; ++i) {
        std::cout << "Vertex " << i << ": " << distance[i] << '\n';

    return 0;


Shortest distances from vertex 0:
Vertex 0: 0
Vertex 1: 10
Vertex 2: 3
Vertex 3: 9


This article gives an outline of two vital calculations for understanding most issues in coordinated and weighted charts. It clarifies the Gullible Recursive approach and Dijkstra's Calculation with Edge Limitations. The Credulous Recursive approach includes recursively investigating all conceivable ways with precisely k edges to discover the most limited way. Dijkstra's Calculation with Edge Imperatives employs a want line and area regulations to successfully find out the maximum confined manner from a supply vertex to all different vertices in the chart.The article incorporates nitty−gritty clarifications of the calculations and gives test code to illustrate their usage.

Updated on: 14-Jul-2023


Kickstart Your Career

Get certified by completing the course

Get Started