Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • C++ Data Types
  • C++ Input/Output
  • C++ Arrays
  • C++ Pointers
  • C++ OOPs
  • C++ STL
  • C++ Interview Questions
  • C++ Programs
  • C++ Cheatsheet
  • C++ MCQ
  • C++ Projects
  • C++ Exception Handling
  • C++ Memory Management
Open In App
Next Article:
Floyd-Warshall Algorithm in C++
Next article icon

Shortest Path Algorithm in C++

Last Updated : 26 Sep, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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++.

Table of Content

  • Types of Shortest Path Algorithms
  • Dijkstra’s Algorithm in C++
  • Bellman-Ford Algorithm in C++
  • Floyd-Warshall Algorithm in C++
  • Johnson’s Algorithm in C++
  • A* Search 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++.

AlgorithmTime ComplexitySpace ComplexityHandles Negative Weights
Dijkstra’sO(V2) or O((V+E)log V) with min-heapO(V)No
Bellman-FordO(V * E)O(V)Yes
A* SearchO(E)O(V)No
Floyd-WarshallO(V³)O(V²)Yes
Johnson’sO(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.

Next Article
Floyd-Warshall Algorithm in C++
author
25anuja
Improve
Article Tags :
  • C++
  • CPP-DSA
Practice Tags :
  • CPP

Similar Reads

  • Shortest Path Algorithm in C
    In C programming, finding the shortest path between nodes in a graph is a common and crucial problem with applications in various fields such as networking, transportation, and logistics. Shortest path algorithms are designed to find the most efficient route from a starting node to a destination nod
    15+ min read
  • Prim's Algorithm in C++
    Prim's Algorithm is a greedy algorithm that is used to find the Minimum Spanning Tree (MST) for a weighted, undirected graph. MST is a subset of the graph's edges that connects all vertices together without any cycles and with the minimum possible total edge weight In this article, we will learn the
    6 min read
  • Johnson Algorithm in C++
    Johnson’s Algorithm is an algorithm used to find the shortest paths between all pairs of vertices in a weighted graph. It is especially useful for sparse graphs and can handle negative weights, provided there are no negative weight cycles. This algorithm uses both Bellman-Ford and Dijkstra's algorit
    8 min read
  • Floyd-Warshall Algorithm in C++
    The Floyd-Warshall algorithm is a dynamic programming technique used to find the shortest paths between all pairs of vertices in a weighted graph. This algorithm is particularly useful for graphs with dense connections and can handle both positive and negative edge weights, though it cannot handle n
    4 min read
  • Convex Hull Algorithm in C++
    The Convex Hull problem is fundamental problem in computational geometry. In this, we need to find the smallest convex polygon, known as the convex hull, that can include a given set of points in a two-dimensional plane. This problem has various applications in areas such as computer graphics, geogr
    15+ min read
  • Algorithm Library Functions in C++ STL
    Non-modifying sequence operations std :: all_of : Test condition on all elements in rangestd :: any_of : Test if any element in range fulfills conditionstd :: none_of : Test if no elements fulfill conditionstd :: for_each : Apply function to rangestd :: find : Find value in rangestd :: find_if : Fin
    4 min read
  • Bellman Ford Algorithm in C++
    The Bellman-Ford algorithm is a single-source shortest path algorithm that finds the shortest path from a given source vertex to all other vertices in a graph. Unlike Dijkstra’s algorithm, Bellman-Ford can handle graphs with negative edge weights, making it useful in various scenarios. In this artic
    5 min read
  • Learn DSA in C++: Master Data Structure and Algorithm in C++
    Data Structures and Algorithms (DSA) are fundamental parts of computer science that allow you to store, organize, and process data in ways that maximize performance. This tutorial will guide you through the important data structures and algorithms using C++ programming language. Why Learn DSA in C++
    9 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
    11 min read
  • Closest Pair of Points in C++
    Closest Pair of Points problem is a classic computational geometry problem. The goal is to find the pair of points with the smallest distance between them in a given set of points in a plane. This problem has practical applications such as air-traffic control, where monitoring planes that come too c
    6 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences