Shortest Path Algorithm in C++
Last Updated :
26 Sep, 2024
The shortest path algorithms are used to find the most efficient route from source node to destination node of a graph in optimal time and space complexities. In this article, we will learn how to implement some commonly used shortest path algorithm in C++.
Types of Shortest Path Algorithms
There is no single algorithm that can solve all types of shortest path problems efficiently due to the different characteristics of graphs. Therefore, we have multiple algorithms to solve specific types of shortest path problems that can be classified into two categories:
Single Source Shortest Path Algorithms
These algorithms find the shortest path from a single source node to all other nodes in the graph. Some of the commonly used algorithms are:
- Depth-First Search (DFS)
- Breadth-First Search (BFS)
- Dijkstra’s Algorithm
- Bellman-Ford Algorithm
- A* Search Algorithm
All Pair Shortest Path Algorithms
Unlike single source algorithms, these algorithms calculate the shortest path between all pairs of nodes.
- Floyd-Warshall Algorithm
- Johnson’s Algorithm
Let's discuss each of these separately.
Dijkstra’s Algorithm in C++
Dijkstra’s algorithm finds the shortest path from a source node to all other nodes in a weighted graph by selecting the node with the smallest distance and updating the distances to its neighbours. It finds the shortest path using a greedy approach while building the shortest path tree.
When to use?
Dijkstra's Algorithm in C++ is used when you need to find the shortest path from a single source node to all other nodes in a weighted graph with non-negative edge weights. This algorithm will not work if the graph has negative edge weight or negative cycle.
Complexity Analysis
Time Complexity: O(E * log(V)) where E is the number of edges and V is the number of vertices.
Auxiliary Space: O(V)
Bellman-Ford Algorithm in C++
The Bellman-Ford algorithm computes the shortest path from a source node to all other nodes in a graph, even in the presence of negative edge weights. It works by relaxing all edges repeatedly, and it can detect negative weight cycles.
When to use?
The Bellman-Ford Algorithm is best used when you need to find the shortest path in a weighted graph that may contain negative edge weights. It is particularly useful when detecting negative weight cycles, which Dijkstra's Algorithm cannot handle.
Complexity Analysis
Time Complexity: O(V * E), where V is the number of vertices and E is the number of edges.
Auxiliary Space: O(V)
Floyd-Warshall Algorithm in C++
The Floyd-Warshall algorithm finds the shortest paths between all pairs of vertices in a weighted graph by considering all possible paths through an intermediate vertex. It can also detect the negative weight cycle.
When to use?
The Floyd-Warshall Algorithm is used to find the shortest paths between all pairs of nodes in a weighted graph. It works for both positive and negative edge weights, but it cannot handle graphs with negative weight cycles. It is also preferred when the graph is dense (many edges), and you are dealing with a relatively small number of vertices.
Complexity Analysis
Time Complexity: O(V3)
Auxiliary Space: O(V2)
Johnson’s Algorithm in C++
Johnson’s algorithm is efficient for sparse graphs. It reweights the graph to remove negative weights using Bellman-Ford and then applies Dijkstra’s algorithm for each vertex.
When to use?
Johnson's Algorithm is used to find the shortest paths between all pairs of nodes in a weighted graph. It is particularly useful when the graph has negative edge weights but no negative weight cycles. It is more efficient for graphs with fewer edges compared to Floyd-Warshall.
Complexity Analysis
Time Complexity: O(V² log V + VE) , Where V is the number of vertices and E is the number of edges.
Auxiliary Space: O(V²) , Where V is the number of vertices.
A* Search Algorithm in C++
The A* search algorithm is an informed search algorithm that finds the shortest path using heuristics to speed up the process. It combines the actual cost from the start node with the estimated cost to the goal node to prioritize nodes.
When to use?
The A* Search Algorithm in C++ is best used when you need to find the shortest path in a weighted graph and you want the algorithm to work efficiently by using a heuristic to guide the search. It is ideal for situations where the graph is large and the search space needs to be narrowed
Complexity Analysis
Time Complexity: O(E), where E is the number of edges.
Auxiliary Space: O(V)
Comparison of Different Shortest Path Algorithms
The below table illustrates the comparison among commonly used shortest path algorithms in C++.
Algorithm | Time Complexity | Space Complexity | Handles Negative Weights |
---|
Dijkstra’s | O(V2) or O((V+E)log V) with min-heap | O(V) | No |
---|
Bellman-Ford | O(V * E) | O(V) | Yes |
---|
A* Search | O(E) | O(V) | No |
---|
Floyd-Warshall | O(V³) | O(V²) | Yes |
---|
Johnson’s | O(V² log V + VE) | O(V²) | Yes |
---|
Applications of Shortest Path Algorithms
Following are the real-world applications of the shortest path algorithms:
- Used to finding the shortest or fastest route between two locations.
- Used for determining the most efficient path for data packets in a computer network.
- Useful in identifying the shortest connections between two individuals.
- Used to path planning for autonomous vehicles or robots.
- To optimize delivery routes or public transportation systems.
Similar Reads
C++ Programming Language C++ is a computer programming language developed by Bjarne Stroustrup as an extension of the C language. It is known for is fast speed, low level memory management and is often taught as first programming language. It provides:Hands-on application of different programming concepts.Similar syntax to
5 min read
Non-linear Components In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
Spring Boot Tutorial Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
Object Oriented Programming in C++ Object Oriented Programming - As the name suggests uses objects in programming. Object-oriented programming aims to implement real-world entities like inheritance, hiding, polymorphism, etc. in programming. The main aim of OOP is to bind together the data and the functions that operate on them so th
5 min read
Class Diagram | Unified Modeling Language (UML) A UML class diagram is a visual tool that represents the structure of a system by showing its classes, attributes, methods, and the relationships between them. It helps everyone involved in a projectâlike developers and designersâunderstand how the system is organized and how its components interact
12 min read
Backpropagation in Neural Network Back Propagation is also known as "Backward Propagation of Errors" is a method used to train neural network . Its goal is to reduce the difference between the modelâs predicted output and the actual output by adjusting the weights and biases in the network.It works iteratively to adjust weights and
9 min read
3-Phase Inverter An inverter is a fundamental electrical device designed primarily for the conversion of direct current into alternating current . This versatile device , also known as a variable frequency drive , plays a vital role in a wide range of applications , including variable frequency drives and high power
13 min read
30 OOPs Interview Questions and Answers [2025 Updated] Object-oriented programming, or OOPs, is a programming paradigm that implements the concept of objects in the program. It aims to provide an easier solution to real-world problems by implementing real-world entities such as inheritance, abstraction, polymorphism, etc. in programming. OOPs concept is
15 min read
Polymorphism in Java Polymorphism in Java is one of the core concepts in object-oriented programming (OOP) that allows objects to behave differently based on their specific class type. The word polymorphism means having many forms, and it comes from the Greek words poly (many) and morph (forms), this means one entity ca
7 min read
What is Vacuum Circuit Breaker? A vacuum circuit breaker is a type of breaker that utilizes a vacuum as the medium to extinguish electrical arcs. Within this circuit breaker, there is a vacuum interrupter that houses the stationary and mobile contacts in a permanently sealed enclosure. When the contacts are separated in a high vac
13 min read