Open In App

How to find Shortest Paths from Source to all Vertices using Dijkstra’s Algorithm

Last Updated : 06 Aug, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow
Solve Problem
Medium
50.83%
1.8L

Given a weighted graph and a source vertex in the graph, find the shortest paths from the source to all the other vertices in the given graph.

Note: The given graph does not contain any negative edge.

Examples:

Input: src = 0, the graph is shown below.

1-(2)

Output: 0 4 12 19 21 11 9 8 14
Explanation: The distance from 0 to 1 = 4.
The minimum distance from 0 to 2 = 12. 0->1->2
The minimum distance from 0 to 3 = 19. 0->1->2->3
The minimum distance from 0 to 4 = 21. 0->7->6->5->4
The minimum distance from 0 to 5 = 11. 0->7->6->5
The minimum distance from 0 to 6 = 9. 0->7->6
The minimum distance from 0 to 7 = 8. 0->7
The minimum distance from 0 to 8 = 14. 0->1->2->8

Dijkstra’s Algorithm using Adjacency Matrix :

The idea is to generate a SPT (shortest path tree) with a given source as a root. Maintain an Adjacency Matrix with two sets,

  • one set contains vertices included in the shortest-path tree,
  • other set includes vertices not yet included in the shortest-path tree.

At every step of the algorithm, find a vertex that is in the other set (set not yet included) and has a minimum distance from the source.

Algorithm :

  • Create a set sptSet (shortest path tree set) that keeps track of vertices included in the shortest path tree, i.e., whose minimum distance from the source is calculated and finalized. Initially, this set is empty.
  • Assign a distance value to all vertices in the input graph. Initialize all distance values as INFINITE . Assign the distance value as 0 for the source vertex so that it is picked first.
  • While sptSet doesn’t include all vertices
    • Pick a vertex u that is not there in sptSet and has a minimum distance value.
    • Include u to sptSet .
    • Then update the distance value of all adjacent vertices of u .
      • To update the distance values, iterate through all adjacent vertices.
      • For every adjacent vertex v, if the sum of the distance value of u (from source) and weight of edge u-v , is less than the distance value of v , then update the distance value of v .

Note: We use a boolean array sptSet[] to represent the set of vertices included in SPT . If a value sptSet[v] is true, then vertex v is included in SPT , otherwise not. Array dist[] is used to store the shortest distance values of all vertices.

Illustration of Dijkstra Algorithm :

To understand the Dijkstra’s Algorithm lets take a graph and find the shortest path from source to all nodes.

Consider below graph and src = 0

1-(2)

Step 1:

  • The set sptSet is initially empty and distances assigned to vertices are {0, INF, INF, INF, INF, INF, INF, INF} where INF indicates infinite.
  • Now pick the vertex with a minimum distance value. The vertex 0 is picked, include it in sptSet . So sptSet becomes {0}. After including 0 to sptSet , update distance values of its adjacent vertices.
  • Adjacent vertices of 0 are 1 and 7. The distance values of 1 and 7 are updated as 4 and 8.

The following subgraph shows vertices and their distance values, only the vertices with finite distance values are shown. The vertices included in SPT are shown in green colour.

6


Step 2:

  • Pick the vertex with minimum distance value and not already included in SPT (not in sptSET ). The vertex 1 is picked and added to sptSet .
  • So sptSet now becomes {0, 1}. Update the distance values of adjacent vertices of 1.
  • The distance value of vertex 2 becomes 12 .
    4


Step 3:

  • Pick the vertex with minimum distance value and not already included in SPT (not in sptSET ). Vertex 7 is picked. So sptSet now becomes {0, 1, 7}.
  • Update the distance values of adjacent vertices of 7. The distance value of vertex 6 and 8 becomes finite ( 15 and 9 respectively).
    5


Step 4:

  • Pick the vertex with minimum distance value and not already included in SPT (not in sptSET ). Vertex 6 is picked. So sptSet now becomes {0, 1, 7, 6} .
  • Update the distance values of adjacent vertices of 6. The distance value of vertex 5 and 8 are updated.
    3-(1)


We repeat the above steps until sptSet includes all vertices of the given graph. Finally, we get the following S hortest Path Tree (SPT).

2-(2)

The Dijkstra algorithm is one of the most important graph algorithms in the DSA but most of the students find it difficult to understand it. In order to have a strong grip on these types of algorithms you can check out our comprehensive course Tech Interview 101 – From DSA to System Design to learn these concepts in detail.

Below is the implementation of the above approach:

C++
// C++ program for Dijkstra's single source shortest path
// algorithm. The program is for adjacency matrix
// representation of the graph
#include <iostream>
using namespace std;
#include <limits.h>

// Number of vertices in the graph
#define V 9

// A utility function to find the vertex with minimum
// distance value, from the set of vertices not yet included
// in shortest path tree
int minDistance(int dist[], bool sptSet[])
{

    // Initialize min value
    int min = INT_MAX, min_index;

    for (int v = 0; v < V; v++)
        if (sptSet[v] == false && dist[v] <= min)
            min = dist[v], min_index = v;

    return min_index;
}

// A utility function to print the constructed distance
// array
void printSolution(int dist[])
{
    cout << "Vertex \t Distance from Source" << endl;
    for (int i = 0; i < V; i++)
        cout << i << " \t\t\t\t" << dist[i] << endl;
}

// Function that implements Dijkstra's single source
// shortest path algorithm for a graph represented using
// adjacency matrix representation
void dijkstra(int graph[V][V], int src)
{
    int dist[V]; // The output array.  dist[i] will hold the
                 // shortest
    // distance from src to i

    bool sptSet[V]; // sptSet[i] will be true if vertex i is
                    // included in shortest
    // path tree or shortest distance from src to i is
    // finalized

    // Initialize all distances as INFINITE and stpSet[] as
    // false
    for (int i = 0; i < V; i++)
        dist[i] = INT_MAX, sptSet[i] = false;

    // Distance of source vertex from itself is always 0
    dist[src] = 0;

    // Find shortest path for all vertices
    for (int count = 0; count < V - 1; count++) {
        // Pick the minimum distance vertex from the set of
        // vertices not yet processed. u is always equal to
        // src in the first iteration.
        int u = minDistance(dist, sptSet);

        // Mark the picked vertex as processed
        sptSet[u] = true;

        // Update dist value of the adjacent vertices of the
        // picked vertex.
        for (int v = 0; v < V; v++)

            // Update dist[v] only if is not in sptSet,
            // there is an edge from u to v, and total
            // weight of path from src to  v through u is
            // smaller than current value of dist[v]
            if (!sptSet[v] && graph[u][v]
                && dist[u] != INT_MAX
                && dist[u] + graph[u][v] < dist[v])
                dist[v] = dist[u] + graph[u][v];
    }

    // print the constructed distance array
    printSolution(dist);
}

// driver's code
int main()
{

    /* Let us create the example graph discussed above */
    int graph[V][V] = { { 0, 4, 0, 0, 0, 0, 0, 8, 0 },
                        { 4, 0, 8, 0, 0, 0, 0, 11, 0 },
                        { 0, 8, 0, 7, 0, 4, 0, 0, 2 },
                        { 0, 0, 7, 0, 9, 14, 0, 0, 0 },
                        { 0, 0, 0, 9, 0, 10, 0, 0, 0 },
                        { 0, 0, 4, 14, 10, 0, 2, 0, 0 },
                        { 0, 0, 0, 0, 0, 2, 0, 1, 6 },
                        { 8, 11, 0, 0, 0, 0, 1, 0, 7 },
                        { 0, 0, 2, 0, 0, 0, 6, 7, 0 } };

    // Function call
    dijkstra(graph, 0);

    return 0;
}

// This code is contributed by shivanisinghss2110
C
// C program for Dijkstra's single source shortest path
// algorithm. The program is for adjacency matrix
// representation of the graph

#include <limits.h>
#include <stdbool.h>
#include <stdio.h>

// Number of vertices in the graph
#define V 9

// A utility function to find the vertex with minimum
// distance value, from the set of vertices not yet included
// in shortest path tree
int minDistance(int dist[], bool sptSet[])
{
    // Initialize min value
    int min = INT_MAX, min_index;

    for (int v = 0; v < V; v++)
        if (sptSet[v] == false && dist[v] <= min)
            min = dist[v], min_index = v;

    return min_index;
}

// A utility function to print the constructed distance
// array
void printSolution(int dist[])
{
    printf("Vertex \t\t Distance from Source\n");
    for (int i = 0; i < V; i++)
        printf("%d \t\t\t\t %d\n", i, dist[i]);
}

// Function that implements Dijkstra's single source
// shortest path algorithm for a graph represented using
// adjacency matrix representation
void dijkstra(int graph[V][V], int src)
{
    int dist[V]; // The output array.  dist[i] will hold the
                 // shortest
    // distance from src to i

    bool sptSet[V]; // sptSet[i] will be true if vertex i is
                    // included in shortest
    // path tree or shortest distance from src to i is
    // finalized

    // Initialize all distances as INFINITE and stpSet[] as
    // false
    for (int i = 0; i < V; i++)
        dist[i] = INT_MAX, sptSet[i] = false;

    // Distance of source vertex from itself is always 0
    dist[src] = 0;

    // Find shortest path for all vertices
    for (int count = 0; count < V - 1; count++) {
        // Pick the minimum distance vertex from the set of
        // vertices not yet processed. u is always equal to
        // src in the first iteration.
        int u = minDistance(dist, sptSet);

        // Mark the picked vertex as processed
        sptSet[u] = true;

        // Update dist value of the adjacent vertices of the
        // picked vertex.
        for (int v = 0; v < V; v++)

            // Update dist[v] only if is not in sptSet,
            // there is an edge from u to v, and total
            // weight of path from src to  v through u is
            // smaller than current value of dist[v]
            if (!sptSet[v] && graph[u][v]
                && dist[u] != INT_MAX
                && dist[u] + graph[u][v] < dist[v])
                dist[v] = dist[u] + graph[u][v];
    }

    // print the constructed distance array
    printSolution(dist);
}

// driver's code
int main()
{
    /* Let us create the example graph discussed above */
    int graph[V][V] = { { 0, 4, 0, 0, 0, 0, 0, 8, 0 },
                        { 4, 0, 8, 0, 0, 0, 0, 11, 0 },
                        { 0, 8, 0, 7, 0, 4, 0, 0, 2 },
                        { 0, 0, 7, 0, 9, 14, 0, 0, 0 },
                        { 0, 0, 0, 9, 0, 10, 0, 0, 0 },
                        { 0, 0, 4, 14, 10, 0, 2, 0, 0 },
                        { 0, 0, 0, 0, 0, 2, 0, 1, 6 },
                        { 8, 11, 0, 0, 0, 0, 1, 0, 7 },
                        { 0, 0, 2, 0, 0, 0, 6, 7, 0 } };

    // Function call
    dijkstra(graph, 0);

    return 0;
}
Java
// A Java program for Dijkstra's single source shortest path
// algorithm. The program is for adjacency matrix
// representation of the graph
import java.io.*;
import java.lang.*;
import java.util.*;

class ShortestPath {
    // A utility function to find the vertex with minimum
    // distance value, from the set of vertices not yet
    // included in shortest path tree
    static final int V = 9;
    int minDistance(int dist[], Boolean sptSet[])
    {
        // Initialize min value
        int min = Integer.MAX_VALUE, min_index = -1;

        for (int v = 0; v < V; v++)
            if (sptSet[v] == false && dist[v] <= min) {
                min = dist[v];
                min_index = v;
            }

        return min_index;
    }

    // A utility function to print the constructed distance
    // array
    void printSolution(int dist[])
    {
        System.out.println(
            "Vertex \t\t Distance from Source");
        for (int i = 0; i < V; i++)
            System.out.println(i + " \t\t " + dist[i]);
    }

    // Function that implements Dijkstra's single source
    // shortest path algorithm for a graph represented using
    // adjacency matrix representation
    void dijkstra(int graph[][], int src)
    {
        int dist[] = new int[V]; // The output array.
                                 // dist[i] will hold
        // the shortest distance from src to i

        // sptSet[i] will true if vertex i is included in
        // shortest path tree or shortest distance from src
        // to i is finalized
        Boolean sptSet[] = new Boolean[V];

        // Initialize all distances as INFINITE and stpSet[]
        // as false
        for (int i = 0; i < V; i++) {
            dist[i] = Integer.MAX_VALUE;
            sptSet[i] = false;
        }

        // Distance of source vertex from itself is always 0
        dist[src] = 0;

        // Find shortest path for all vertices
        for (int count = 0; count < V - 1; count++) {
            // Pick the minimum distance vertex from the set
            // of vertices not yet processed. u is always
            // equal to src in first iteration.
            int u = minDistance(dist, sptSet);

            // Mark the picked vertex as processed
            sptSet[u] = true;

            // Update dist value of the adjacent vertices of
            // the picked vertex.
            for (int v = 0; v < V; v++)

                // Update dist[v] only if is not in sptSet,
                // there is an edge from u to v, and total
                // weight of path from src to v through u is
                // smaller than current value of dist[v]
                if (!sptSet[v] && graph[u][v] != 0
                    && dist[u] != Integer.MAX_VALUE
                    && dist[u] + graph[u][v] < dist[v])
                    dist[v] = dist[u] + graph[u][v];
        }

        // print the constructed distance array
        printSolution(dist);
    }

    // Driver's code
    public static void main(String[] args)
    {
        /* Let us create the example graph discussed above
         */
        int graph[][]
            = new int[][] { { 0, 4, 0, 0, 0, 0, 0, 8, 0 },
                            { 4, 0, 8, 0, 0, 0, 0, 11, 0 },
                            { 0, 8, 0, 7, 0, 4, 0, 0, 2 },
                            { 0, 0, 7, 0, 9, 14, 0, 0, 0 },
                            { 0, 0, 0, 9, 0, 10, 0, 0, 0 },
                            { 0, 0, 4, 14, 10, 0, 2, 0, 0 },
                            { 0, 0, 0, 0, 0, 2, 0, 1, 6 },
                            { 8, 11, 0, 0, 0, 0, 1, 0, 7 },
                            { 0, 0, 2, 0, 0, 0, 6, 7, 0 } };
        ShortestPath t = new ShortestPath();

        // Function call
        t.dijkstra(graph, 0);
    }
}
// This code is contributed by Aakash Hasija
Python
# Python program for Dijkstra's single
# source shortest path algorithm. The program is
# for adjacency matrix representation of the graph

# Library for INT_MAX
import sys


class Graph():

    def __init__(self, vertices):
        self.V = vertices
        self.graph = [[0 for column in range(vertices)]
                      for row in range(vertices)]

    def printSolution(self, dist):
        print("Vertex \tDistance from Source")
        for node in range(self.V):
            print(node, "\t", dist[node])

    # A utility function to find the vertex with
    # minimum distance value, from the set of vertices
    # not yet included in shortest path tree
    def minDistance(self, dist, sptSet):

        # Initialize minimum distance for next node
        min = sys.maxsize

        # Search not nearest vertex not in the
        # shortest path tree
        for u in range(self.V):
            if dist[u] < min and sptSet[u] == False:
                min = dist[u]
                min_index = u

        return min_index

    # Function that implements Dijkstra's single source
    # shortest path algorithm for a graph represented
    # using adjacency matrix representation
    def dijkstra(self, src):

        dist = [sys.maxsize] * self.V
        dist[src] = 0
        sptSet = [False] * self.V

        for cout in range(self.V):

            # Pick the minimum distance vertex from
            # the set of vertices not yet processed.
            # x is always equal to src in first iteration
            x = self.minDistance(dist, sptSet)

            # Put the minimum distance vertex in the
            # shortest path tree
            sptSet[x] = True

            # Update dist value of the adjacent vertices
            # of the picked vertex only if the current
            # distance is greater than new distance and
            # the vertex in not in the shortest path tree
            for y in range(self.V):
                if self.graph[x][y] > 0 and sptSet[y] == False and \
                        dist[y] > dist[x] + self.graph[x][y]:
                    dist[y] = dist[x] + self.graph[x][y]

        self.printSolution(dist)


# Driver's code
if __name__ == "__main__":
    g = Graph(9)
    g.graph = [[0, 4, 0, 0, 0, 0, 0, 8, 0],
               [4, 0, 8, 0, 0, 0, 0, 11, 0],
               [0, 8, 0, 7, 0, 4, 0, 0, 2],
               [0, 0, 7, 0, 9, 14, 0, 0, 0],
               [0, 0, 0, 9, 0, 10, 0, 0, 0],
               [0, 0, 4, 14, 10, 0, 2, 0, 0],
               [0, 0, 0, 0, 0, 2, 0, 1, 6],
               [8, 11, 0, 0, 0, 0, 1, 0, 7],
               [0, 0, 2, 0, 0, 0, 6, 7, 0]
               ]

    g.dijkstra(0)

# This code is contributed by Divyanshu Mehta and Updated by Pranav Singh Sambyal
C#
// C# program for Dijkstra's single
// source shortest path algorithm.
// The program is for adjacency matrix
// representation of the graph
using System;

class GFG {
    // A utility function to find the
    // vertex with minimum distance
    // value, from the set of vertices
    // not yet included in shortest
    // path tree
    static int V = 9;
    int minDistance(int[] dist, bool[] sptSet)
    {
        // Initialize min value
        int min = int.MaxValue, min_index = -1;

        for (int v = 0; v < V; v++)
            if (sptSet[v] == false && dist[v] <= min) {
                min = dist[v];
                min_index = v;
            }

        return min_index;
    }

    // A utility function to print
    // the constructed distance array
    void printSolution(int[] dist)
    {
        Console.Write("Vertex \t\t Distance "
                      + "from Source\n");
        for (int i = 0; i < V; i++)
            Console.Write(i + " \t\t " + dist[i] + "\n");
    }

    // Function that implements Dijkstra's
    // single source shortest path algorithm
    // for a graph represented using adjacency
    // matrix representation
    void dijkstra(int[, ] graph, int src)
    {
        int[] dist
            = new int[V]; // The output array. dist[i]
        // will hold the shortest
        // distance from src to i

        // sptSet[i] will true if vertex
        // i is included in shortest path
        // tree or shortest distance from
        // src to i is finalized
        bool[] sptSet = new bool[V];

        // Initialize all distances as
        // INFINITE and stpSet[] as false
        for (int i = 0; i < V; i++) {
            dist[i] = int.MaxValue;
            sptSet[i] = false;
        }

        // Distance of source vertex
        // from itself is always 0
        dist[src] = 0;

        // Find shortest path for all vertices
        for (int count = 0; count < V - 1; count++) {
            // Pick the minimum distance vertex
            // from the set of vertices not yet
            // processed. u is always equal to
            // src in first iteration.
            int u = minDistance(dist, sptSet);

            // Mark the picked vertex as processed
            sptSet[u] = true;

            // Update dist value of the adjacent
            // vertices of the picked vertex.
            for (int v = 0; v < V; v++)

                // Update dist[v] only if is not in
                // sptSet, there is an edge from u
                // to v, and total weight of path
                // from src to v through u is smaller
                // than current value of dist[v]
                if (!sptSet[v] && graph[u, v] != 0
                    && dist[u] != int.MaxValue
                    && dist[u] + graph[u, v] < dist[v])
                    dist[v] = dist[u] + graph[u, v];
        }

        // print the constructed distance array
        printSolution(dist);
    }

    // Driver's Code
    public static void Main()
    {
        /* Let us create the example
graph discussed above */
        int[, ] graph
            = new int[, ] { { 0, 4, 0, 0, 0, 0, 0, 8, 0 },
                            { 4, 0, 8, 0, 0, 0, 0, 11, 0 },
                            { 0, 8, 0, 7, 0, 4, 0, 0, 2 },
                            { 0, 0, 7, 0, 9, 14, 0, 0, 0 },
                            { 0, 0, 0, 9, 0, 10, 0, 0, 0 },
                            { 0, 0, 4, 14, 10, 0, 2, 0, 0 },
                            { 0, 0, 0, 0, 0, 2, 0, 1, 6 },
                            { 8, 11, 0, 0, 0, 0, 1, 0, 7 },
                            { 0, 0, 2, 0, 0, 0, 6, 7, 0 } };
        GFG t = new GFG();

        // Function call
        t.dijkstra(graph, 0);
    }
}

// This code is contributed by ChitraNayal
JavaScript
// A Javascript program for Dijkstra's single 
// source shortest path algorithm. 
// The program is for adjacency matrix 
// representation of the graph     
let V = 9;

// A utility function to find the 
// vertex with minimum distance 
// value, from the set of vertices 
// not yet included in shortest 
// path tree 
function minDistance(dist,sptSet)
{
    
    // Initialize min value 
    let min = Number.MAX_VALUE;
    let min_index = -1;
    
    for(let v = 0; v < V; v++)
    {
        if (sptSet[v] == false && dist[v] <= min) 
        {
            min = dist[v];
            min_index = v;
        }
    }
    return min_index;
}

// A utility function to print 
// the constructed distance array 
function printSolution(dist)
{
    console.log("Vertex \t\t Distance from Source<br>");
    for(let i = 0; i < V; i++)
    {
        console.log(i + " \t\t " + 
                 dist[i] + "<br>");
    }
}

// Function that implements Dijkstra's 
// single source shortest path algorithm 
// for a graph represented using adjacency 
// matrix representation 
function dijkstra(graph, src)
{
    let dist = new Array(V);
    let sptSet = new Array(V);
    
    // Initialize all distances as 
    // INFINITE and stpSet[] as false 
    for(let i = 0; i < V; i++)
    {
        dist[i] = Number.MAX_VALUE;
        sptSet[i] = false;
    }
    
    // Distance of source vertex 
    // from itself is always 0 
    dist[src] = 0;
    
    // Find shortest path for all vertices 
    for(let count = 0; count < V - 1; count++)
    {
        
        // Pick the minimum distance vertex 
        // from the set of vertices not yet 
        // processed. u is always equal to 
        // src in first iteration. 
        let u = minDistance(dist, sptSet);
        
        // Mark the picked vertex as processed 
        sptSet[u] = true;
        
        // Update dist value of the adjacent 
        // vertices of the picked vertex. 
        for(let v = 0; v < V; v++)
        {
            
            // Update dist[v] only if is not in 
            // sptSet, there is an edge from u 
            // to v, and total weight of path 
            // from src to v through u is smaller 
            // than current value of dist[v] 
            if (!sptSet[v] && graph[u][v] != 0 && 
                   dist[u] != Number.MAX_VALUE &&
                   dist[u] + graph[u][v] < dist[v])
            {
                dist[v] = dist[u] + graph[u][v];
            }
        }
    }
    
    // Print the constructed distance array
    printSolution(dist);
}

// Driver code
let graph = [ [ 0, 4, 0, 0, 0, 0, 0, 8, 0 ],
              [ 4, 0, 8, 0, 0, 0, 0, 11, 0 ],
              [ 0, 8, 0, 7, 0, 4, 0, 0, 2 ],
              [ 0, 0, 7, 0, 9, 14, 0, 0, 0],
              [ 0, 0, 0, 9, 0, 10, 0, 0, 0 ],
              [ 0, 0, 4, 14, 10, 0, 2, 0, 0],
              [ 0, 0, 0, 0, 0, 2, 0, 1, 6 ],
              [ 8, 11, 0, 0, 0, 0, 1, 0, 7 ],
              [ 0, 0, 2, 0, 0, 0, 6, 7, 0 ] ]
dijkstra(graph, 0);

// This code is contributed by rag2127

Output
Vertex      Distance from Source
0                 0
1                 4
2                 12
3                 19
4                 21
5                 11
6                 9
7                 8
8                 14

Time Complexity: O(V 2 )
Auxiliary Space: O(V)

Notes:

  • The code calculates the shortest distance but doesn’t calculate the path information. Create a parent array, update the parent array when distance is updated and use it to show the shortest path from source to different vertices.
  • The time Complexity of the implementation is O(V 2 ) . If the input graph is represented using adjacency list , it can be reduced to O(E * log V) with the help of a binary heap. Please see Dijkstra’s Algorithm for Adjacency List Representation for more details.
  • Dijkstra’s algorithm doesn’t work for graphs with negative weight cycles.

Why Dijkstra’s Algorithms fails for the Graphs having Negative Edges ?

The problem with negative weights arises from the fact that Dijkstra’s algorithm assumes that once a node is added to the set of visited nodes, its distance is finalized and will not change. However, in the presence of negative weights, this assumption can lead to incorrect results.

Consider the following graph for the example:

Failure-of-Dijkstra-in-case-of-negative-edges

In the above graph, A is the source node, among the edges A to B and A to C , A to B is the smaller weight and Dijkstra assigns the shortest distance of B as 2, but because of existence of a negative edge from C to B , the actual shortest distance reduces to 1 which Dijkstra fails to detect.

Note: We use Bellman Ford’s Shortest path algorithm in case we have negative edges in the graph.

Dijkstra’s Algorithm using Adjacency List in O(E logV):

For Dijkstra’s algorithm, it is always recommended to use Heap (or priority queue ) as the required operations (extract minimum and decrease key) match with the speciality of the heap (or priority queue). However, the problem is, that priority_queue doesn’t support the decrease key. To resolve this problem, do not update a key, but insert one more copy of it. So we allow multiple instances of the same vertex in the priority queue. This approach doesn’t require decreasing key operations and has below important properties.

  • Whenever the distance of a vertex is reduced, we add one more instance of a vertex in priority_queue. Even if there are multiple instances, we only consider the instance with minimum distance and ignore other instances.
  • The time complexity remains O(E * LogV) as there will be at most O(E) vertices in the priority queue and O(logE) is the same as O(logV)

Below is the implementation of the above approach:

C++
#include <bits/stdc++.h>
using namespace std;

// Define INF as a large value to represent infinity
#define INF 0x3f3f3f3f

// iPair ==> Integer Pair
typedef pair<int, int> iPair;

// Class representing a graph using adjacency list representation
class Graph {
    int V; // Number of vertices
    list<iPair> *adj; // Adjacency list

public:
    Graph(int V); // Constructor

    void addEdge(int u, int v, int w); // Function to add an edge
    void shortestPath(int s); // Function to print shortest path from source
};

// Constructor to allocate memory for the adjacency list
Graph::Graph(int V) {
    this->V = V;
    adj = new list<iPair>[V];
}

// Function to add an edge to the graph
void Graph::addEdge(int u, int v, int w) {
    adj[u].push_back(make_pair(v, w));
    adj[v].push_back(make_pair(u, w)); // Since the graph is undirected
}

// Function to print shortest paths from source
void Graph::shortestPath(int src) {
    // Create a priority queue to store vertices being processed
    // Priority queue sorted by the first element of the pair (distance)
    priority_queue<iPair, vector<iPair>, greater<iPair>> pq;

    // Create a vector to store distances and initialize all distances as INF
    vector<int> dist(V, INF);

    // Insert source into priority queue and initialize its distance as 0
    pq.push(make_pair(0, src));
    dist[src] = 0;

    // Process the priority queue
    while (!pq.empty()) {
        // Get the vertex with the minimum distance
        int u = pq.top().second;
        pq.pop();

        // Iterate through all adjacent vertices of the current vertex
        for (auto &neighbor : adj[u]) {
            int v = neighbor.first;
            int weight = neighbor.second;

            // If a shorter path to v is found
            if (dist[v] > dist[u] + weight) {
                // Update distance and push new distance to the priority queue
                dist[v] = dist[u] + weight;
                pq.push(make_pair(dist[v], v));
            }
        }
    }

    // Print the shortest distances
    cout << "Vertex Distance from Source" << endl;
    for (int i = 0; i < V; ++i)
        cout << i << " \t\t " << dist[i] << endl;
}

// Driver's code
int main() {
    int V = 9; // Number of vertices
    Graph g(V);

    // Add edges to the graph
    g.addEdge(0, 1, 4);
    g.addEdge(0, 7, 8);
    g.addEdge(1, 2, 8);
    g.addEdge(1, 7, 11);
    g.addEdge(2, 3, 7);
    g.addEdge(2, 8, 2);
    g.addEdge(2, 5, 4);
    g.addEdge(3, 4, 9);
    g.addEdge(3, 5, 14);
    g.addEdge(4, 5, 10);
    g.addEdge(5, 6, 2);
    g.addEdge(6, 7, 1);
    g.addEdge(6, 8, 6);
    g.addEdge(7, 8, 7);

    // Call the shortestPath function
    g.shortestPath(0);

    return 0;
}
Java
import java.util.*;

class Graph {
    private int V;
    private List<List<iPair>> adj;

    Graph(int V) {
        this.V = V;
        adj = new ArrayList<>();
        for (int i = 0; i < V; i++) {
            adj.add(new ArrayList<>());
        }
    }

    void addEdge(int u, int v, int w) {
        adj.get(u).add(new iPair(v, w));
        adj.get(v).add(new iPair(u, w));
    }

    void shortestPath(int src) {
        PriorityQueue<iPair> pq = new PriorityQueue<>(V, Comparator.comparingInt(o -> o.second));
        int[] dist = new int[V];
        Arrays.fill(dist, Integer.MAX_VALUE);

        pq.add(new iPair(0, src));
        dist[src] = 0;

        while (!pq.isEmpty()) {
            int u = pq.poll().second;

            for (iPair v : adj.get(u)) {
                if (dist[v.first] > dist[u] + v.second) {
                    dist[v.first] = dist[u] + v.second;
                    pq.add(new iPair(dist[v.first], v.first));
                }
            }
        }

        System.out.println("Vertex Distance from Source");
        for (int i = 0; i < V; i++) {
            System.out.println(i + "\t\t" + dist[i]);
        }
    }

    static class iPair {
        int first, second;

        iPair(int first, int second) {
            this.first = first;
            this.second = second;
        }
    }
}

public class Main {
    public static void main(String[] args) {
        int V = 9;
        Graph g = new Graph(V);

        g.addEdge(0, 1, 4);
        g.addEdge(0, 7, 8);
        g.addEdge(1, 2, 8);
        g.addEdge(1, 7, 11);
        g.addEdge(2, 3, 7);
        g.addEdge(2, 8, 2);
        g.addEdge(2, 5, 4);
        g.addEdge(3, 4, 9);
        g.addEdge(3, 5, 14);
        g.addEdge(4, 5, 10);
        g.addEdge(5, 6, 2);
        g.addEdge(6, 7, 1);
        g.addEdge(6, 8, 6);
        g.addEdge(7, 8, 7);

        g.shortestPath(0);
    }
}
Python
import heapq

# iPair ==> Integer Pair
iPair = tuple

# This class represents a directed graph using
# adjacency list representation
class Graph:
    def __init__(self, V: int): # Constructor
        self.V = V
        self.adj = [[] for _ in range(V)]

    def addEdge(self, u: int, v: int, w: int):
        self.adj[u].append((v, w))
        self.adj[v].append((u, w))

    # Prints shortest paths from src to all other vertices
    def shortestPath(self, src: int):
        # Create a priority queue to store vertices that
        # are being preprocessed
        pq = []
        heapq.heappush(pq, (0, src))

        # Create a vector for distances and initialize all
        # distances as infinite (INF)
        dist = [float('inf')] * self.V
        dist[src] = 0

        while pq:
            # The first vertex in pair is the minimum distance
            # vertex, extract it from priority queue.
            # vertex label is stored in second of pair
            d, u = heapq.heappop(pq)

            # 'i' is used to get all adjacent vertices of a
            # vertex
            for v, weight in self.adj[u]:
                # If there is shorted path to v through u.
                if dist[v] > dist[u] + weight:
                    # Updating distance of v
                    dist[v] = dist[u] + weight
                    heapq.heappush(pq, (dist[v], v))

        # Print shortest distances stored in dist[]
        for i in range(self.V):
            print(f"{i} \t\t {dist[i]}")

# Driver's code
if __name__ == "__main__":
    # create the graph given in above figure
    V = 9
    g = Graph(V)

    # making above shown graph
    g.addEdge(0, 1, 4)
    g.addEdge(0, 7, 8)
    g.addEdge(1, 2, 8)
    g.addEdge(1, 7, 11)
    g.addEdge(2, 3, 7)
    g.addEdge(2, 8, 2)
    g.addEdge(2, 5, 4)
    g.addEdge(3, 4, 9)
    g.addEdge(3, 5, 14)
    g.addEdge(4, 5, 10)
    g.addEdge(5, 6, 2)
    g.addEdge(6, 7, 1)
    g.addEdge(6, 8, 6)
    g.addEdge(7, 8, 7)

    g.shortestPath(0)
C#
using System;
using System.Collections.Generic;

// This class represents a directed graph using
// adjacency list representation
public class Graph
{
  private const int INF = 2147483647;

  private int V;
  private List<int[]>[] adj;

  public Graph(int V)
  {    
    // No. of vertices
    this.V = V;
    // In a weighted graph, we need to store vertex
    // and weight pair for every edge
    this.adj = new List<int[]>[V];

    for (int i = 0; i < V; i++)
    {
      this.adj[i] = new List<int[]>();
    }
  }

  public void AddEdge(int u, int v, int w)
  {
    this.adj[u].Add(new int[] { v, w });
    this.adj[v].Add(new int[] { u, w });
  }

  // Prints shortest paths from src to all other vertices
  public void ShortestPath(int src)
  {
    // Create a priority queue to store vertices that
    // are being preprocessed.
    SortedSet<int[]> pq = new SortedSet<int[]>(new DistanceComparer());

    // Create an array for distances and initialize all
    // distances as infinite (INF)
    int[] dist = new int[V];
    for (int i = 0; i < V; i++)
    {
      dist[i] = INF;
    }

    // Insert source itself in priority queue and initialize
    // its distance as 0.
    pq.Add(new int[] { 0, src });
    dist[src] = 0;

    /* Looping till priority queue becomes empty (or all
        distances are not finalized) */
    while (pq.Count > 0)
    {
      // The first vertex in pair is the minimum distance
      // vertex, extract it from priority queue.
      // vertex label is stored in second of pair (it
      // has to be done this way to keep the vertices
      // sorted by distance)
      int[] minDistVertex = pq.Min;
      pq.Remove(minDistVertex);
      int u = minDistVertex[1];

      // 'i' is used to get all adjacent vertices of a
      // vertex
      foreach (int[] adjVertex in this.adj[u])
      {
        // Get vertex label and weight of current
        // adjacent of u.
        int v = adjVertex[0];
        int weight = adjVertex[1];

        // If there is a shorter path to v through u.
        if (dist[v] > dist[u] + weight)
        {
          // Updating distance of v
          dist[v] = dist[u] + weight;
          pq.Add(new int[] { dist[v], v });
        }
      }
    }

    // Print shortest distances stored in dist[]
    Console.WriteLine("Vertex Distance from Source");
    for (int i = 0; i < V; ++i)
      Console.WriteLine(i + "\t" + dist[i]);
  }

  private class DistanceComparer : IComparer<int[]>
  {
    public int Compare(int[] x, int[] y)
    {
      if (x[0] == y[0])
      {
        return x[1] - y[1];
      }
      return x[0] - y[0];
    }
  }
}

public class Program
{    
  // Driver Code
  public static void Main()
  {
    // create the graph given in above figure
    int V = 9;
    Graph g = new Graph(V);

    // making above shown graph
    g.AddEdge(0, 1, 4);
    g.AddEdge(0, 7, 8);
    g.AddEdge(1, 2, 8);
    g.AddEdge(1, 7, 11);
    g.AddEdge(2, 3, 7);
    g.AddEdge(2, 8, 2);
    g.AddEdge(2, 5, 4);
    g.AddEdge(3, 4, 9);
    g.AddEdge(3, 5, 14);
    g.AddEdge(4, 5, 10);
    g.AddEdge(5, 6, 2);
    g.AddEdge(6, 7, 1);
    g.AddEdge(6, 8, 6);
    g.AddEdge(7, 8, 7);
    g.ShortestPath(0);
  }
}

// this code is contributed by bhardwajji
JavaScript
// javascript Program to find Dijkstra's shortest path using
// priority_queue in STL
const INF = 2147483647;

// This class represents a directed graph using
// adjacency list representation
class Graph {
    
    constructor(V){
        
        // No. of vertices
        this.V = V;
        
        // In a weighted graph, we need to store vertex
        // and weight pair for every edge
        this.adj = new Array(V);
        for(let i = 0; i < V; i++){
            this.adj[i] = new Array();
        }
    }

    addEdge(u, v, w)
    {
        this.adj[u].push([v, w]);
        this.adj[v].push([u, w]);
    }

    // Prints shortest paths from src to all other vertices
    shortestPath(src)
    {
        // Create a priority queue to store vertices that
        // are being preprocessed. This is weird syntax in C++.
        // Refer below link for details of this syntax
        // https://www.geeksforgeeks.org/implement-min-heap-using-stl/
        let pq = [];

        // Create a vector for distances and initialize all
        // distances as infinite (INF)
        let dist = new Array(V).fill(INF);

        // Insert source itself in priority queue and initialize
        // its distance as 0.
        pq.push([0, src]);
        dist[src] = 0;

        /* Looping till priority queue becomes empty (or all
        distances are not finalized) */
        while (pq.length > 0) {
            // The first vertex in pair is the minimum distance
            // vertex, extract it from priority queue.
            // vertex label is stored in second of pair (it
            // has to be done this way to keep the vertices
            // sorted distance (distance must be first item
            // in pair)
            let u = pq[0][1];
            pq.shift();

            // 'i' is used to get all adjacent vertices of a
            // vertex
            for(let i = 0; i < this.adj[u].length; i++){
                
                // Get vertex label and weight of current
                // adjacent of u.
                let v = this.adj[u][i][0];
                let weight = this.adj[u][i][1];

                // If there is shorted path to v through u.
                if (dist[v] > dist[u] + weight) {
                    // Updating distance of v
                    dist[v] = dist[u] + weight;
                    pq.push([dist[v], v]);
                    pq.sort((a, b) =>{
                        if(a[0] == b[0]) return a[1] - b[1];
                        return a[0] - b[0];
                    });
                }
            }
        }

        // Print shortest distances stored in dist[]
        console.log("Vertex Distance from Source");
        for (let i = 0; i < V; ++i)
            console.log(i, "        ", dist[i]);
    }
}

// Driver's code
// create the graph given in above figure
let V = 9;
let g = new Graph(V);

// making above shown graph
g.addEdge(0, 1, 4);
g.addEdge(0, 7, 8);
g.addEdge(1, 2, 8);
g.addEdge(1, 7, 11);
g.addEdge(2, 3, 7);
g.addEdge(2, 8, 2);
g.addEdge(2, 5, 4);
g.addEdge(3, 4, 9);
g.addEdge(3, 5, 14);
g.addEdge(4, 5, 10);
g.addEdge(5, 6, 2);
g.addEdge(6, 7, 1);
g.addEdge(6, 8, 6);
g.addEdge(7, 8, 7);

// Function call
g.shortestPath(0);

// The code is contributed by Nidhi goel. 

Output
Vertex Distance from Source
0          0
1          4
2          12
3          19
4          21
5          11
6          9
7          8
8          14

Time Complexity: O(E * logV), Where E is the number of edges and V is the number of vertices.
Auxiliary Space: O(V)

Applications of Dijkstra’s Algorithm:

  • Google maps uses Dijkstra algorithm to show shortest distance between source and destination.
  • In computer networking , Dijkstra’s algorithm forms the basis for various routing protocols, such as OSPF (Open Shortest Path First) and IS-IS (Intermediate System to Intermediate System).
  • Transportation and traffic management systems use Dijkstra’s algorithm to optimize traffic flow, minimize congestion, and plan the most efficient routes for vehicles.
  • Airlines use Dijkstra’s algorithm to plan flight paths that minimize fuel consumption, reduce travel time.
  • Dijkstra’s algorithm is applied in electronic design automation for routing connections on integrated circuits and very-large-scale integration (VLSI) chips.

For a more detailed explanation refer to this article Dijkstra’s Shortest Path Algorithm using priority_queue of STL .



Previous Article
Next Article

Similar Reads

Printing Paths in Dijkstra's Shortest Path Algorithm
Given a graph and a source vertex in the graph, find the shortest paths from the source to all vertices in the given graph.We have discussed Dijkstra's Shortest Path algorithm in the below posts.  Dijkstra’s shortest path for adjacency matrix representationDijkstra’s shortest path for adjacency list representationThe implementations discussed above
15 min read
Shortest paths from all vertices to a destination
Given a Weighted Directed Graph and a destination vertex in the graph, find the shortest distance from all vertex to the destination vertex.Input : Output : 0 6 10 7 5Distance of 0 from 0: 0 Distance of 0 from 1: 1+5 = 6 (1->4->0) Distance of 0 from 2: 10 (2->0) Distance of 0 from 3: 1+1+5 = 7 (3->1->4->0) Distance of 0 from 4: 5
11 min read
Dijkstra’s shortest path algorithm using set in STL
Given a graph and a source vertex in graph, find shortest paths from source to all vertices in the given graph. Input : Source = 0Output : Vertex Distance from Source 0 0 1 4 2 12 3 19 4 21 5 11 6 9 7 8 8 14We have discussed Dijkstra's shortest Path implementations. Dijkstra’s Algorithm for Adjacency Matrix Representation (In C/C++ with time comple
13 min read
Dijkstra's Shortest Path Algorithm using priority_queue of STL
Given a graph and a source vertex in graph, find shortest paths from source to all vertices in the given graph. Input : Source = 0Output : Vertex Distance from Source 0 0 1 4 2 12 3 19 4 21 5 11 6 9 7 8 8 14We have discussed Dijkstra’s shortest Path implementations. Dijkstra’s Algorithm for Adjacency Matrix Representation (In C/C++ with time comple
15+ min read
Print all shortest paths between given source and destination in an undirected graph
Given an undirected and unweighted graph and two nodes as source and destination, the task is to print all the paths of the shortest length between the given source and destination.Examples: Input: source = 0, destination = 5 Output: 0 -> 1 -> 3 -> 50 -> 2 -> 3 -> 50 -> 1 -> 4 -> 5 Explanation: All the above paths are of
13 min read
Applications of Dijkstra's shortest path algorithm
Dijkstra’s algorithm is one of the most popular algorithms for solving many single-source shortest path problems having non-negative edge weight in the graphs i.e., it is to find the shortest distance between two vertices on a graph. It was conceived by computer scientist Edsger W. Dijkstra in 1956 and published three years later. Dijkstra’s Algori
4 min read
Johnson’s algorithm for All-pairs shortest paths | Implementation
Given a weighted Directed Graph where the weights may be negative, find the shortest path between every pair of vertices in the Graph using Johnson's Algorithm.  The detailed explanation of Johnson's algorithm has already been discussed in the previous post.  Refer Johnson’s algorithm for All-pairs shortest paths.  This post focusses on the impleme
12 min read
Implementation of Johnson’s algorithm for all-pairs shortest paths
Johnson's algorithm finds the shortest paths between all pairs of vertices in a weighted directed graph. It allows some of the edge weights to be negative numbers, but no negative-weight cycles may exist. It uses the Bellman-Ford algorithm to re-weight the original graph, removing all negative weights. Dijkstra's algorithm is applied on the re-weig
14 min read
Johnson's algorithm for All-pairs shortest paths
The problem is to find the shortest paths between every pair of vertices in a given weighted directed Graph and weights may be negative. We have discussed Floyd Warshall Algorithm for this problem.  The time complexity of the Floyd Warshall Algorithm is Θ(V3).  Using Johnson's algorithm, we can find all pair shortest paths in O(V2log V + VE) time.
15+ min read
Edge Relaxation Property for Dijkstra’s Algorithm and Bellman Ford's Algorithm
In the field of graph theory, various shortest path algorithms especially Dijkstra’s algorithm and Bellmann-Ford’s algorithm repeatedly employ the use of the technique called Edge Relaxation. The idea of relaxation is the same in both algorithms and it is by understanding, the 'Relaxation property' we can fully grasp the working of the two algorith
4 min read
Difference Between Dijkstra's Algorithm and A* Search Algorithm
Dijkstra's Algorithm and A* Algorithm are two of the most widely used techniques. Both are employed to the find the shortest path between the nodes in a graph but they have distinct differences in their approaches and applications. Understanding these differences is crucial for the selecting the appropriate algorithm for the given problem. What is
3 min read
Find all remaining vertices in Graph after marking shortest path for neighbours
Given an undirected graph with V vertices in the form of an adjacency matrix, the weight of any two edges cannot be the same. For each vertex mark vertex that is connected to it via the edge of the lowest weight, the task is to return all the unmarked vertices. Return -1 if every vertex is marked. Examples: Input: V = 3, A[][] = {{0, 10, 50}, {10,
7 min read
Find K vertices in the graph which are connected to at least one of remaining vertices
Given a connected graph with N vertices. The task is to select k(k must be less than or equals to n/2, not necessarily minimum) vertices from the graph such that all these selected vertices are connected to at least one of the non selected vertex. In case of multiple answers print any one of them. Examples: Input : Output : 1 Vertex 1 is connected
8 min read
Find the remaining vertices of a square from two given vertices
Given the coordinates of any two vertices of a square (X1, Y1) and (X2, Y2), the task is to find the coordinates of the other two vertices. If a square cannot be formed using these two vertices, print -1. Examples: Input: X1 = 1, Y1 = 2, X2 = 3, Y2 = 4 Output: (1, 4), (3, 2) Explanation: From the above figure the other two vertices of the square wi
6 min read
Find three vertices in an N-sided regular polygon such that the angle subtended at a vertex by two other vertices is closest to A
Given an N-sided regular convex polygon and an angle A in degrees, the task is to find any 3 vertices i, j, and k, such that the angle subtended at vertex j by vertex i and k is closest to A. Note: Each vertex is numbered from 1 to N in an anticlockwise direction starting from any vertex. Examples: Input: N = 3, A = 15Output: 2 1 3Explanation:The g
7 min read
Print all paths from a source point to all the 4 corners of a Matrix
Given a 2D array arr[][] of size M*N containing 1s and 0s where 1 represents that the cell can be visited and 0s represent that the cell is blocked. There is a source point (x, y) and the task is to print all the paths from the given source to any of the four corners of the array (0, 0), (0, N - 1), (M - 1, 0) and (M - 1, N - 1). Examples: Input: a
15 min read
Dijkstra's shortest path with minimum edges
Prerequisite: Dijkstra’s shortest path algorithm Given an adjacency matrix graph representing paths between the nodes in the given graph. The task is to find the shortest path with minimum edges i.e. if there a multiple short paths with same cost then choose the one with the minimum number of edges. Consider the graph given below: There are two pat
13 min read
Difference between BFS and Dijkstra's algorithms when looking for shortest path?
What is Dijkstra's Algorithm? Dijkstra's Algorithm is used for finding the shortest path between any two vertices of a graph. It uses a priority queue for finding the shortest path. For more detail about Dijkstra's Algorithm, you can refer to this article. What is BFS Algorithm? Breadth First Search (BFS) algorithm traverses a graph in a bread towa
2 min read
Count all possible Paths between two Vertices
Count the total number of ways or paths that exist between two vertices in a directed graph. These paths don't contain a cycle, the simple enough reason is that a cycle contains an infinite number of paths and hence they create a problem Examples: For the following Graph: Input: Count paths between A and EOutput: Total paths between A and E are 4Ex
9 min read
D'Esopo-Pape Algorithm : Single Source Shortest Path
Given a graph and a source vertex src in a weighted undirected graph, find the shortest paths from src to all vertices in the given graph. The graph may contain negative weight edges. For this problem, we have already discussed Dijkstra's algorithm and Bellman-Ford Algorithm. But D'Esopo-Pape Algorithm performs quite well in most of the cases. Howe
11 min read
Maximize the number of uncolored vertices appearing along the path from root vertex and the colored vertices
Given a tree with N vertices numbered 1 through N with vertex 1 as root vertex and N - 1 edges. We have to color exactly k number of vertices and count the number of uncolored vertices between root vertex and every colored vertex. We have to include the root vertex in the count if it is not colored. The task to maximize the number of uncolored vert
8 min read
Pendant Vertices, Non-Pendant Vertices, Pendant Edges and Non-Pendant Edges in Graph
Pre-requisites: Handshaking theorem. Pendant Vertices Let G be a graph, A vertex v of G is called a pendant vertex if and only if v has degree 1. In other words, pendant vertices are the vertices that have degree 1, also called pendant vertex. Note: Degree = number of edges connected to a vertex In the case of trees, a pendant vertex is known as a
7 min read
Find maximum number of edge disjoint paths between two vertices
Given a directed graph and two vertices in it, source 's' and destination 't', find out the maximum number of edge disjoint paths from s to t. Two paths are said edge disjoint if they don't share any edge. There can be maximum two edge disjoint paths from source 0 to destination 7 in the above graph. Two edge disjoint paths are highlighted below in
15+ min read
Print all paths from a given source to a destination using BFS
Given a directed graph, a source vertex ‘src’ and a destination vertex ‘dst’, print all paths from given ‘src’ to ‘dst’. Please note that in the cases, we have cycles in the graph, we need not to consider paths have cycles as in case of cycles, there can by infinitely many by doing multiple iterations of a cycle. For simplicity, you may assume that
9 min read
Minimum steps to convert all paths in matrix from top left to bottom right as palindromic paths
Given a matrix mat[][] with N rows and M columns. The task is to find the minimum number of changes required in the matrix such that every path from top left to bottom right is a palindromic path. In a path only right and bottom movements are allowed from one cell to another cell.Examples: Input: mat[][] = {{1, 2}, {3, 1}} Output: 0 Explanation: Ev
15+ min read
Minimum steps to convert all paths in matrix from top left to bottom right as palindromic paths | Set 2
Given a matrix mat[][] with N rows and M columns. The task is to find the minimum number of changes required in the matrix such that every path from top left to bottom right is a palindromic path. In a path only right and bottom movements are allowed from one cell to another cell. Examples: Input: M = 2, N = 2, mat[M][N] = {{0, 0}, {0, 1}} Output:
12 min read
Count of all unique paths from given source to destination in a Matrix
Given a 2D matrix of size n*m, a source ‘s’ and a destination ‘d’, print the count of all unique paths from given ‘s’ to ‘d’. From each cell, you can either move only to the right or down. Examples: Input: arr[][] = { {1, 2, 3}, {4, 5, 6} }, s = {0, 0}, d = {1, 2}Output: 3Explanation: All possible paths from source to destination are: 1 -> 4 -
4 min read
Print all unique paths from given source to destination in a Matrix moving only down or right
Given a 2-D array mat[][], a source ‘s’ and a destination ‘d’, print all unique paths from given ‘s’ to ‘d’. From each cell, you can either move only to the right or down. Examples: Input: mat[][] = {{1, 2, 3}, {4, 5, 6}}, s[] = {0, 0}, d[]={1, 2}Output: 1 4 5 61 2 5 61 2 3 6 Input: mat[][] = {{1, 2}, {3, 4}}, s[] = {0, 1}, d[] = {1, 1}Output: 2 4
6 min read
Print all paths from a given source to a destination
Given a directed graph, a source vertex 's' and a destination vertex 'd', print all paths from given 's' to 'd'. Consider the following directed graph. Let the s be 2 and d be 3. There are 3 different paths from 2 to 3.  Recommended PracticeCount the pathsTry It!Approach: The idea is to do Depth First Traversal of a given directed graph.Start the D
10 min read
Minimize flips required to make all shortest paths from top-left to bottom-right of a binary matrix equal to S
Given a binary matrix mat[][] having dimensions N * M and a binary string S of length N + M - 1 , the task is to find the minimum number of flips required to make all shortest paths from the top-left cell to the bottom-right cell equal to the given string S. Examples: Input: mat[][] = [[1, 0, 1, 1], [1, 1, 1, 0]], S = "10010"Output: 3 Explanation:
6 min read