- Blog Categories
- Software Development Projects and Ideas
- 12 Computer Science Project Ideas
- 28 Beginner Software Projects
- Top 10 Engineering Project Ideas
- Top 10 Easy Final Year Projects
- Top 10 Mini Projects for Engineers
- 25 Best Django Project Ideas
- Top 20 MERN Stack Project Ideas
- Top 12 Real Time Projects
- Top 6 Major CSE Projects
- 12 Robotics Projects for All Levels
- Java Programming Concepts
- Abstract Class in Java and Methods
- Constructor Overloading in Java
- StringBuffer vs StringBuilder
- Java Identifiers: Syntax & Examples
- Types of Variables in Java Explained
- Composition in Java: Examples
- Append in Java: Implementation
- Loose Coupling vs Tight Coupling
- Integrity Constraints in DBMS
- Different Types of Operators Explained
- Career and Interview Preparation in IT
- Top 14 IT Courses for Jobs
- Top 20 Highest Paying Languages
- 23 Top CS Interview Q&A
- Best IT Jobs without Coding
- Software Engineer Salary in India
- 44 Agile Methodology Interview Q&A
- 10 Software Engineering Challenges
- Top 15 Tech's Daily Life Impact
- 10 Best Backends for React
- Cloud Computing Reference Models
- Web Development and Security
- Find Installed NPM Version
- Install Specific NPM Package Version
- Make API Calls in Angular
- Install Bootstrap in Angular
- Use Axios in React: Guide
- StrictMode in React: Usage
- 75 Cyber Security Research Topics
- Top 7 Languages for Ethical Hacking
- Top 20 Docker Commands
- Advantages of OOP
- Data Science Projects and Applications
- 42 Python Project Ideas for Beginners
- 13 Data Science Project Ideas
- 13 Data Structure Project Ideas
- 12 Real-World Python Applications
- Python Banking Project
- Data Science Course Eligibility
- Association Rule Mining Overview
- Cluster Analysis in Data Mining
- Classification in Data Mining
- KDD Process in Data Mining
- Data Structures and Algorithms
- Binary Tree Types Explained
- Binary Search Algorithm
- Sorting in Data Structure
- Binary Tree in Data Structure
- Binary Tree vs Binary Search Tree
- Recursion in Data Structure
- Data Structure Search Methods: Explained
- Binary Tree Interview Q&A
- Linear vs Binary Search
- Priority Queue Overview
- Python Programming and Tools
- Top 30 Python Pattern Programs
- List vs Tuple
- Python Free Online Course
- Method Overriding in Python
- Top 21 Python Developer Skills
- Reverse a Number in Python
- Switch Case Functions in Python
- Info Retrieval System Overview
- Reverse a Number in Python
- Real-World Python Applications
- Data Science Careers and Comparisons
- Data Analyst Salary in India
- Data Scientist Salary in India
- Free Excel Certification Course
- Actuary Salary in India
- Data Analyst Interview Guide
- Pandas Interview Guide
- Tableau Filters Explained
- Data Mining Techniques Overview
- Data Analytics Lifecycle Phases
- Data Science Vs Analytics Comparison
- Artificial Intelligence and Machine Learning Projects
- Exciting IoT Project Ideas
- 16 Exciting AI Project Ideas
- 45+ Interesting ML Project Ideas
- Exciting Deep Learning Projects
- 12 Intriguing Linear Regression Projects
- 13 Neural Network Projects
- 5 Exciting Image Processing Projects
- Top 8 Thrilling AWS Projects
- 12 Engaging AI Projects in Python
- NLP Projects for Beginners
- Concepts and Algorithms in AIML
- Basic CNN Architecture Explained
- 6 Types of Regression Models
- Data Preprocessing Steps
- Bagging vs Boosting in ML
- Multinomial Naive Bayes Overview
- Gini Index for Decision Trees
- Bayesian Network Example
- Bayes Theorem Guide
- Top 10 Dimensionality Reduction Techniques
- Neural Network Step-by-Step Guide
- Technical Guides and Comparisons
- Make a Chatbot in Python
- Compute Square Roots in Python
- Permutation vs Combination
- Image Segmentation Techniques
- Generative AI vs Traditional AI
- AI vs Human Intelligence
- Random Forest vs Decision Tree
- Neural Network Overview
- Perceptron Learning Algorithm
- Selection Sort Algorithm
- Career and Practical Applications in AIML
- AI Salary in India Overview
- Biological Neural Network Basics
- Top 10 AI Challenges
- Production System in AI
- Top 8 Raspberry Pi Alternatives
- Top 8 Open Source Projects
- 14 Raspberry Pi Project Ideas
- 15 MATLAB Project Ideas
- Top 10 Python NLP Libraries
- Naive Bayes Explained
- Digital Marketing Projects and Strategies
- 10 Best Digital Marketing Projects
- 17 Fun Social Media Projects
- Top 6 SEO Project Ideas
- Digital Marketing Case Studies
- Coca-Cola Marketing Strategy
- Nestle Marketing Strategy Analysis
- Zomato Marketing Strategy
- Monetize Instagram Guide
- Become a Successful Instagram Influencer
- 8 Best Lead Generation Techniques
- Digital Marketing Careers and Salaries
- Digital Marketing Salary in India
- Top 10 Highest Paying Marketing Jobs
- Highest Paying Digital Marketing Jobs
- SEO Salary in India
- Brand Manager Salary in India
- Content Writer Salary Guide
- Digital Marketing Executive Roles
- Career in Digital Marketing Guide
- Future of Digital Marketing
- MBA in Digital Marketing Overview
- Digital Marketing Techniques and Channels
- 9 Types of Digital Marketing Channels
- Top 10 Benefits of Marketing Branding
- 100 Best YouTube Channel Ideas
- YouTube Earnings in India
- 7 Reasons to Study Digital Marketing
- Top 10 Digital Marketing Objectives
- 10 Best Digital Marketing Blogs
- Top 5 Industries Using Digital Marketing
- Growth of Digital Marketing in India
- Top Career Options in Marketing
- Interview Preparation and Skills
- 73 Google Analytics Interview Q&A
- 56 Social Media Marketing Q&A
- 78 Google AdWords Interview Q&A
- Top 133 SEO Interview Q&A
- 27+ Digital Marketing Q&A
- Digital Marketing Free Course
- Top 9 Skills for PPC Analysts
- Movies with Successful Social Media Campaigns
- Marketing Communication Steps
- Top 10 Reasons to Be an Affiliate Marketer
- Career Options and Paths
- Top 25 Highest Paying Jobs India
- Top 25 Highest Paying Jobs World
- Top 10 Highest Paid Commerce Job
- Career Options After 12th Arts
- Top 7 Commerce Courses Without Maths
- Top 7 Career Options After PCB
- Best Career Options for Commerce
- Career Options After 12th CS
- Top 10 Career Options After 10th
- 8 Best Career Options After BA
- Projects and Academic Pursuits
- 17 Exciting Final Year Projects
- Top 12 Commerce Project Topics
- Top 13 BCA Project Ideas
- Career Options After 12th Science
- Top 15 CS Jobs in India
- 12 Best Career Options After M.Com
- 9 Best Career Options After B.Sc
- 7 Best Career Options After BCA
- 22 Best Career Options After MCA
- 16 Top Career Options After CE
- Courses and Certifications
- 10 Best Job-Oriented Courses
- Best Online Computer Courses
- Top 15 Trending Online Courses
- Top 19 High Salary Certificate Courses
- 21 Best Programming Courses for Jobs
- What is SGPA? Convert to CGPA
- GPA to Percentage Calculator
- Highest Salary Engineering Stream
- 15 Top Career Options After Engineering
- 6 Top Career Options After BBA
- Job Market and Interview Preparation
- Why Should You Be Hired: 5 Answers
- Top 10 Future Career Options
- Top 15 Highest Paid IT Jobs India
- 5 Common Guesstimate Interview Q&A
- Average CEO Salary: Top Paid CEOs
- Career Options in Political Science
- Top 15 Highest Paying Non-IT Jobs
- Cover Letter Examples for Jobs
- Top 5 Highest Paying Freelance Jobs
- Top 10 Highest Paying Companies India
- Career Options and Paths After MBA
- 20 Best Careers After B.Com
- Career Options After MBA Marketing
- Top 14 Careers After MBA In HR
- Top 10 Highest Paying HR Jobs India
- How to Become an Investment Banker
- Career Options After MBA - High Paying
- Scope of MBA in Operations Management
- Best MBA for Working Professionals India
- MBA After BA - Is It Right For You?
- Best Online MBA Courses India
- MBA Project Ideas and Topics
- 11 Exciting MBA HR Project Ideas
- Top 15 MBA Project Ideas
- 18 Exciting MBA Marketing Projects
- MBA Project Ideas: Consumer Behavior
- What is Brand Management?
- What is Holistic Marketing?
- What is Green Marketing?
- Intro to Organizational Behavior Model
- Tech Skills Every MBA Should Learn
- Most Demanding Short Term Courses MBA
- MBA Salary, Resume, and Skills
- MBA Salary in India
- HR Salary in India
- Investment Banker Salary India
- MBA Resume Samples
- Sample SOP for MBA
- Sample SOP for Internship
- 7 Ways MBA Helps Your Career
- Must-have Skills in Sales Career
- 8 Skills MBA Helps You Improve
- Top 20+ SAP FICO Interview Q&A
- MBA Specializations and Comparative Guides
- Why MBA After B.Tech? 5 Reasons
- How to Answer 'Why MBA After Engineering?'
- Why MBA in Finance
- MBA After BSc: 10 Reasons
- Which MBA Specialization to choose?
- Top 10 MBA Specializations
- MBA vs Masters: Which to Choose?
- Benefits of MBA After CA
- 5 Steps to Management Consultant
- 37 Must-Read HR Interview Q&A
- Fundamentals and Theories of Management
- What is Management? Objectives & Functions
- Nature and Scope of Management
- Decision Making in Management
- Management Process: Definition & Functions
- Importance of Management
- What are Motivation Theories?
- Tools of Financial Statement Analysis
- Negotiation Skills: Definition & Benefits
- Career Development in HRM
- Top 20 Must-Have HRM Policies
- Project and Supply Chain Management
- Top 20 Project Management Case Studies
- 10 Innovative Supply Chain Projects
- Latest Management Project Topics
- 10 Project Management Project Ideas
- 6 Types of Supply Chain Models
- Top 10 Advantages of SCM
- Top 10 Supply Chain Books
- What is Project Description?
- Top 10 Project Management Companies
- Best Project Management Courses Online
- Salaries and Career Paths in Management
- Project Manager Salary in India
- Average Product Manager Salary India
- Supply Chain Management Salary India
- Salary After BBA in India
- PGDM Salary in India
- Top 7 Career Options in Management
- CSPO Certification Cost
- Why Choose Product Management?
- Product Management in Pharma
- Product Design in Operations Management
- Industry-Specific Management and Case Studies
- Amazon Business Case Study
- Service Delivery Manager Job
- Product Management Examples
- Product Management in Automobiles
- Product Management in Banking
- Sample SOP for Business Management
- Video Game Design Components
- Top 5 Business Courses India
- Free Management Online Course
- SCM Interview Q&A
- Fundamentals and Types of Law
- Acceptance in Contract Law
- Offer in Contract Law
- 9 Types of Evidence
- Types of Law in India
- Introduction to Contract Law
- Negotiable Instrument Act
- Corporate Tax Basics
- Intellectual Property Law
- Workmen Compensation Explained
- Lawyer vs Advocate Difference
- Law Education and Courses
- LLM Subjects & Syllabus
- Corporate Law Subjects
- LLM Course Duration
- Top 10 Online LLM Courses
- Online LLM Degree
- Step-by-Step Guide to Studying Law
- Top 5 Law Books to Read
- Why Legal Studies?
- Pursuing a Career in Law
- How to Become Lawyer in India
- Career Options and Salaries in Law
- Career Options in Law India
- Corporate Lawyer Salary India
- How To Become a Corporate Lawyer
- Career in Law: Starting, Salary
- Career Opportunities: Corporate Law
- Business Lawyer: Role & Salary Info
- Average Lawyer Salary India
- Top Career Options for Lawyers
- Types of Lawyers in India
- Steps to Become SC Lawyer in India
- Tutorials
- C Tutorials
- Recursion in C: Fibonacci Series
- Checking String Palindromes in C
- Prime Number Program in C
- Implementing Square Root in C
- Matrix Multiplication in C
- Understanding Double Data Type
- Factorial of a Number in C
- Structure of a C Program
- Building a Calculator Program in C
- Compiling C Programs on Linux
- Java Tutorials
- Handling String Input in Java
- Determining Even and Odd Numbers
- Prime Number Checker
- Sorting a String
- User-Defined Exceptions
- Understanding the Thread Life Cycle
- Swapping Two Numbers
- Using Final Classes
- Area of a Triangle
- Skills
- Software Engineering
- JavaScript
- Data Structure
- React.js
- Core Java
- Node.js
- Blockchain
- SQL
- Full stack development
- Devops
- NFT
- BigData
- Cyber Security
- Cloud Computing
- Database Design with MySQL
- Cryptocurrency
- Python
- Digital Marketings
- Advertising
- Influencer Marketing
- Search Engine Optimization
- Performance Marketing
- Search Engine Marketing
- Email Marketing
- Content Marketing
- Social Media Marketing
- Display Advertising
- Marketing Analytics
- Web Analytics
- Affiliate Marketing
- MBA
- MBA in Finance
- MBA in HR
- MBA in Marketing
- MBA in Business Analytics
- MBA in Operations Management
- MBA in International Business
- MBA in Information Technology
- MBA in Healthcare Management
- MBA In General Management
- MBA in Agriculture
- MBA in Supply Chain Management
- MBA in Entrepreneurship
- MBA in Project Management
- Management Program
- Consumer Behaviour
- Supply Chain Management
- Financial Analytics
- Introduction to Fintech
- Introduction to HR Analytics
- Fundamentals of Communication
- Art of Effective Communication
- Introduction to Research Methodology
- Mastering Sales Technique
- Business Communication
- Fundamentals of Journalism
- Economics Masterclass
- Free Courses
Dijkstra’s Shortest Path Algorithm – A Detailed Overview
Updated on 10 October, 2023
3.32K+ views
• 17 min read
Table of Contents
- What Is Dijkstra Algorithm Shortest Path Algorithm: Explained with Examples
- Understanding Graphs
- Introduction to Dijkstra’s Algorithm
- Why Do We Use Dijkstra’s Algorithm?
- A Step-by-Step Guide to Implementing Dijkstra’s Algorithm
- Dijkstra’s Shortest Path Algorithm Example
- Understanding Pseudocode for Dijkstra’s Algorithm
- Using Dijkstra’s Algorithm in Various Programming Languages
- Real-life Applications of Dijkstra’s Algorithm
- Pros and Cons of Dijkstra’s Algorithm
- Conclusion
What Is Dijkstra Algorithm Shortest Path Algorithm: Explained with Examples
The Dutch computer scientist Edsger Dijkstra in 1959, spoke about the shortest path algorithm that could be applied to a weighted graph. This graph can be of two types – directed or undirected. A precondition of the graph is that there should be a non-negative value on its very edge. Edsger named this algorithm ‘Dijkstra’s Algorithm’.
This blog will explore Dijkstra’s shortest path algorithm and ways to implement it in various programming languages.
Understanding Graphs
Graphs are non-linear data structures depicting the connections between elements known as vertices or nodes. The arcs or lines forming the connection between two nodes in a graph are termed edges. Simply put, a graph comprises a set of Edges (E) and vertices (V). This graph can be denoted G (V, E). Two graph nodes connect only when an edge exists between them.
Graph components
- Edges – Edges, also called arcs, are lines connecting two vertices or graph nodes. These are.
- Vertices – Basic graph elements, also known as nodes, vertices depict real-life people and objects.
Graph Types
Graphs can be broadly classified into directed and undirected graphs.
1. Directed Graph
These graphs consist of edges with direction. The edges denote a one-way relationship in such graphs where a single direction traverses each edge. The figure above shows a simple directed graph consisting of five edges and four nodes. Arrows are used in place of simple lines to denote directed edges.
2. Undirected Graphs
Graphs with an edge but no fixed direction are known as undirected graphs. In these graphs, the edge denotes a two-way relationship where we can communicate in both directions. The figure above shows a simple undirected graph comprising six edges and six nodes. Learn more about this topic in our detailed blog post
Weighted Graph
Weighted graphs are those where each edge is assigned a ‘weight’ or ‘cost.’ This weight can represent time, distance or anything representing the connection between the nodes or vertices it links. Dijkstra’s Algorithm considers these weights as essential elements.
The image above shows the weighted graph with a number beside each edge, signifying the weight of the corresponding edge.
Introduction to Dijkstra’s Algorithm
Alternately called single source shortest path algorithm, Dijkstra’s Algorithm is used to figure out the shortest path in weighted graphs or the shortest distance between the starting node and target node in weighted graphs. It uses the weights of the edges to find the route that minimises the total weight or distance between the starting node and the other nodes.
This algorithmic process provides the shortest distance from a precise source node to all other nodes inside a graph. This differs from the minimum spanning tree since the shortest path between two nodes might not include all the graph nodes.
Why Do We Use Dijkstra’s Algorithm?
Dijkstra’s Algorithm is used in GPS devices to find the shortest path between your current location and your destination. Additionally, Dijkstra’s Algorithm in computer networks is used for routing protocols.
A Step-by-Step Guide to Implementing Dijkstra’s Algorithm
Look at some of the important features of the algorithm before moving on to Dijkstra’s Algorithm steps for implementing the algorithm.
- Dijkstra’s Algorithm starts from the source node. The algorithm examines the whole graph to find the shortest path between that node and all other nodes.
- It keeps track of the presently recognised shortest path from each node to the starting node. It updates the values if it can find a different shortest path.
- After the algorithm has found the shortest distance from the source node to another node, it marks the node as ‘visited’ and adds it to the path.
- This process continues until the path contains all nodes in the graph. With the help of this, a path is created connecting the source node to all other nodes. This path is created following the probable shortest distance to reach each node.
Let’s move on to the step-by-step process of implementing Dijkstra’s Algorithm.
- Mark all vertices as unvisited.
- Mark the source node with a present distance of 0 while marking the other nodes as infinity.
- Fix the source node as the current node.
- Analyse all the unvisited neighbours of the current node and calculate their distances. Add the present distance of the current node to the edge’s (connecting current node and neighbour node) weight to calculate the distance.
- Compare the most recent distance to the distance already assigned to the neighbouring node, then set that distance as the new current distance for that node.
- Consider all the current node’s unvisited neighbours after that and mark the current node as visited.
- An algorithm has ended if the destination node has been marked as visited.
- If not, select the unvisited node marked with the smallest distance and fix it as the latest current node. Repeat the process once more from step 4.
Dijkstra’s Shortest Path Algorithm Example
For a better understanding, consider the illustration below to explain Dijkstra’s Algorithm with examples.
- Begin with a weighted graph.
- Select a source node and mark it as 0. Assign infinity to the other nodes.
- Move to each node and update the path distance.
- If the path distance of the adjacent node is smaller than the new path distance, it is unnecessary to update it.
- You must avoid updating the path distances of nodes you have visited.
- We choose the unvisited node with the smallest path distance after each iteration. That is why choose 5 before 7.
- You may notice how the rightmost node gets its path distance updated twice.
- Repeat the steps until all the nodes have been visited.
Understanding Pseudocode for Dijkstra’s Algorithm
Now that we have a fair grasp of Dijkstra Algorithm example, let’s dive into the pseudocode for Dijkstra Algorithm.
- Keep a record of the path length of every vertex. Keep each vertex’s path length inside an array with size n, where n is the total number of vertices.
- Find the shortest path and the distance of that path. To overcome this issue, map each vertex to the vertex that last updated its path distance.
- After completing the algorithm, try backtracking the destination vertex to the source vertex to find the path.
- Use a minimum Priority Queue to find the vertex with the smallest path length efficiently.
Now look at this pseudocode of the above example.
Pseudocode:
function Dijkstra Algorithm(Graph, source node)
// iterating through the nodes in Graph and set their distances to INFINITY
for each node N in Graph:
distance[N] = INFINITY
previous N = NULL
If N != source_node, add N to Priority Queue G // setting the distance of the source node of the Graph to 0
distance source_node]=0
// iterating until the Priority Queue G is not empty
while G is NOT empty:
// selecting a node Q having the least distance and marking it as visited
Q = node in G with the least distance
mark Q visited
// iterating through the unvisited neighbouring nodes of the node Q and performing
relaxation accordingly
for each unvisited neighbour node N of Q
temporary distance = distance[Q] + distance between(Q, N)
if the temporary distance is less than the given distance of the path to the Node.
updating the resultant distance with the minimum value
if temporary distance < distance[N]
distance[N]:= temporary distance
previousNO
//returning the final list of distance
return distance[], previous[]
In the pseudocode above, a function is built with two parameters — the source node and the Graph made up of the nodes. In this function, each node in the Graph has been iterated through their initial distance set to INFINITY, and the previous node value set to NULL. Additionally, before adding each node to the priority queue, it was checked to confirm it was not a source node.
The source node’s length is set to 0. After going through each node in the priority queue once, the closest one is chosen and marked as visited. It is repeated through the selected node’s unexplored neighbours and relaxed wherever necessary.
Finally, the original and temporary distances between the source and destination nodes are compared and updated with the resulting distance with the minimum value and the prior node information. For the last step, we returned the final list of distances with the prior node information.
Check out our free technology courses to get an edge over the competition.
Using Dijkstra’s Algorithm in Various Programming Languages
This section will describe the implementation of the algorithm in various programming languages.
Dijkstra’s Algorithm C Code
Use the following code to implement Dijkstra Algorithm in C.
File: DijkstraAlgorithm.c
// Implementation of Dijkstra's Algorithm in C
// importing the standard I/O header file
#include <stdio.h>
// defining some constants
#define INF 9999
#define MAX 10
// prototyping of the function
void DijkstraAlgorithm(int Graph[MAX][MAX], int size, int start);
// defining the function for Dijkstra's Algorithm
void DijkstraAlgorithm(int Graph[MAX][MAX], int size, int start) {
int cost[MAX][MAX], distance[MAX], previous[MAX];
int visited_nodes[MAX], counter, minimum_distance, next_node, i, JE
// creating cost matrix
for (i = 0; i < size; i++)
for (j = 0; j < size; j++)
if (Graphi [i][j] == 0)
cost[i][j] = INF;
else
cost[i][j]= Graphjn:[i][j];
for (i = 0; i < size; i++) {
distance[i] = cost[start][i];
previous[i] = start;
visited_nodes[i] = 0;
}
distance[start] = 0;
visited_nodes[start] = 1;
counter = 1;
while (counter < size - 1) {
minimum distance = INF;
for (i = 0; i < size; i++)
if (distance[i] < minimum_distance && !visited_nodes[j]) {
minimum distance = distance[i];
next_node = i;
}
visited_nodes[next_node] =1;
for (i = 0; i < size; i++)
if (!visited_nodes[i])
if (minimum_distance + cost[next_node][i] < distance[i]) {
distance[i] = minimum_distance + cost[next_node][i];
previous[i] = next_node;
}
counter++;
}
// printing the distance
for (i=0; i< size; i++)
if (i != start) {
printf("\nDistance from the Source Node to %d: %d", i, distance[i]);
}
}
// main function
int main(){
// defining variables
int Graph[MAX][MAX], i, j, size, source;
// declaring the size of the matrix
size = 7;
// declaring the nodes of graph
Graph[0][0] = 0;
Graph[0][1] = 4;
Graph[0][2] = 0;
Graph[0][3] = 0;
Graph[0][4] = 0;
Graph[0][5] = 8;
Graph[0][6] = 0;
Graph[1][0] = 4;
Graph[1][1] <= 0;
Graph[1][2] = 8:
Graph[1][3] = 0:
Graph[1][4] = 0;
Graph[1][5] = 11;
Graph[1][6] = 0;
Graph[2][0] = 0;
Graph[2][1] = 8:
Graph[2][2] <= 0;
Graph[2][3] = 7:
Graph[2][4] = 0;
Graph [2][5] = 4;
Graph[2][6] = 0;
Graph[3][0] = 0;
Graph [3][1] = 0;
Graph[3][2] <= 7
Graph[3][3] <=0
Graph[3][4] = 9,
Graph[3]][5] = 14;
Graph[3][6]= 0;
Graph [4][0] = 0;
Graph [4][1] = 0;
Graph[4][2] = 0;
Graph[4][3]= 9;
Graph[4][4] = 0;
Graph[4][5] = 10;
Graph[4][6] = 2:
Graph[5][0] = 0;
Graph[5][1] = 0;
Graph[5][2] = 4;
Graph [5][3] = 14
Graph [5][4] = 10;
Graph [5][5]= 0;
Graph[5][6]= 2;
Graph[6][0] = 0;
Graph[6][1]=0;
Graph[6][2] = 0;
Graph[6][3] = 0;
Graph[6][4] = 2;
Graph[8][5] = 0;
Graph[8][6] = 1;
source= 0;
//calling the DijkstraAlgorithm() function by passing the Graph, the number of nodes and
the source node
Dijkstra Algorithm(Graph, size, source);
return 0;
}
Read our Popular Articles related to Software
Dijkstra Algorithm C++ Code
Use the following code to implement Dijkstra’s Algorithm in C++.
File: DijkstraAlgorithm.cpp
// Implementation of Dijkstra's Algorithm in C++
// importing the required header files
#include <iostream>
#include <vector>
// defining constant
#define MAX_INT 10000000
// using the standard namespace
using namespace std;
// prototyping of the DijkstraAlgorithm() function
void DijkstraAlgorithm();
// main function
int main(){
DijkstraAlgorithm();
return 0;
}
// declaring the classes
class Vertex;
class Edge;
// prototyping the functions
void Dijkstra();
vector<Vertex*>* Adjacent Remaining Nodes(Vertex" vertex);
Vertex Extract_Smallest(vector<Vertex*>& vertices);
int Distance(Vertex vertexOne, Vertex* vertexTwo);
bool Contains(vector<Vertex">& vertices, Vertex vertex);
vold Print Shortest Route To(Vertex" des);
// instantiating the classes
vector<Vertex"> vertices;
vector<Edge"> edges;
// defining the class for the vertices of the graph
class Vertex{
public:
Vertex(char id)
: id(id), prev(NULL), distance_from_start(MAX_INT) {
vertices.push_back(this);
}
public:
char id;
Vertex* prev;
int distance_from_start;
};
// defining the class for the edges of the graph
class Edge {
public:
Edge(Vertex* vertexOne, Vertex vertexTwo, int distance)
: vertexOne(vertexOne), vertexTwo(vertexTwo), distance(distance) {
edges.push_back(this);
}
bool Connects(Vertex* vertexOne, Vertex vertexTwo) {
return(
(vertexOne == this->vertexOne &&
vertex Two == this->vertexTwo) ||
(vertexOne == this->vertexTwo &&
vertexTwo == this->vertexOne));
}
public:
Vertex vertexOne:
Vertex vertexTwo:
int distance;
};
// defining the function to collect the details of the graph
void DijkstraAlgorithm() {
// declaring some vertices
Vertex vertex_a= new Vertex('A');
Vertex vertex_b = new Vertex('B');
Vertex vertex_c = new Vertex('C');
Vertex vertex_d = new Vertex('D');
Vertex vertex_e = new Vertex('E');
Vertex vertex_f = new Vertex('F');
Vertex vertex_g = new Vertex('G');
// declaring some edges
Edge* edge_1 = new Edge(vertex a, vertex_c, 1);
Edge* edge_2 = new Edge(vertex a, vertex_d, 2);
Edge* edge_3 = new Edge(vertex b, vertex_c, 2);
Edge* edge_4 = new Edge(vertex c, vertex_d, 1):
Edge* edge_5 = new Edge(vertex b, vertex_f, 3);
Edge* edge_6 = new Edge(vertex c, vertex_e, 3);
Edge* edge_7 = new Edge(vertex e, vertex_f, 2);
Edge* edge_8 = new Edge(vertex d, vertex_g, 1);
Edge* edge_9= new Edge(vertex g, vertex_f, 1);
vertex a distance from start = 0; // setting a start vertex
// calling the Dijkstra() function to find the shortest route possible
Dijkstra();
//calling the prient_shortest_route_to() function to print the shortest route from the
Source vertex to the destination vertex
Print_shortest_Route_To(vertex_f);
// defining the function for Dijkstra's Algorithmn
void Dijkstra(){
while (vertices.size() > 0) {
Vertex smallest = Extract Smallest(vertices);
vector<Vertex adjacent nodes =
Adjacent_Remaining_Nodes(smallest);
const int size = adjacent_nodes -> size();
for (int i = 0; i < size; ++i) {
Vertex adjacent = adjacent nodes → at);
int distance = Distance(smallest, adjacent) +
smallest -> distance_from_start;
if (distance < adjacent -> distance_from_start) {
adjacent->distance from start = distance:
adjacent -> prev = smallest;
}
}
delete adjacent_nodes;
}
}
// defining the function to find the vertex with the shortest distance, removing it, and
returning it
Vertex* Extract Smallest(vector<Vertex">& vertices) int size = vertices.size();
if (size == 0) return NULL;
int smallest_position = 0;
Vertex* smallest = vertices.at(0);
for (int i = 1; i < size; ++i) {
Vertex* current = vertices.at(i);
if (current ->distance_from_start <
smallest -> distance_from_start)
smallest=current;
smallest_position=i;
}
}
vertices.erase(vertices.begin() + smallest_position);
return smallest;
}
// defining the function to return all vertices adjacent to 'vertex' which are still in the
vertices collection.
vector<Vertex*>* Adjacent Remaining Nodes(Vertex" vertex) {
vector<Vertex"> adjacent nodes = new vector<Vertex">();
const int size = edges.size();
for (int i = 0; i < size; ++i) {
Edge* edge = edges.at(i);
Vertex adjacent = NULL;
if (edge -> vertexOne == vertex) {
adjacent = edge >> vertexTwo;
}else if (edge -> vertexTwo == vertex) {
adjacent = edge-> vertexOne;
}
if (adjacent && Contains(vertices, adjacent)) {
adjacent nodes -> push_back(adjacent);
}
}
return adjacent nodes;
}
// defining the function to return distance between two connected vertices
int Distance(Vertex* vertexOne, Vertex* vertexTwo) {
const int size = edges.size();
for (int i = 0; i < size; ++i) {
Edge* edge = edges.at(i);
if (edge -> Connects(vertexOne, vertexTwo)) {
return edge -> distance;
}
}
return -1; // should never happen
}
// defining the function to check if the 'vertices' vector contains 'vertex'
bool Contains(vector<Vertex*>& vertices, Vertex* vertex) {
const int size = vertices.size();
for (int i = 0; i < size; ++i) {
if (vertex == vertices.at(i)) {}
return true;
}
}
return false;
}
// defining the function to print the shortest route to the destination
vold Print_Shortest_Route _To(Vertex* des) {
Vertex" prev = des;
cout << "Distance from start: "
<< des -> distance_from_start << endl;
while (prev) {
cout << prev -> id <<"";
prev = prev-> prev;
}
cout << endl;
}
Dijkstra Algorithm Java Code
Use the following code to implement Dijkstra’s Algorithm in Java programming language.
File: DijkstraAlgorithm.java
// Implementation of Dijkstra's Algorithm in Java
// defining the public class for Dijkstra's Algorithm
public class DijkstraAlgorithm {
// defining the method to implement Dijkstra's Algorithm
public void dijkstraAlgorithm(int[][] graph, int source) {
// number of nodes
int nodes = graph.length;
boolean[] visited_vertex = new boolean[nodes];
int[] dist = new int[nodes];
for (int i=0; i<nodes; i++){
visited_vertex] = false;
dist[i] = Integer.MAX_VALUE;
}
// Distance of self loop is zero
dist[source] = 0;
for (int i=0; i<nodes, i++) {
//Updating the distance between neighbouring vertex and source vertex
int u= find_min_distance(dist, visited vertex);
visited_vertex[u] = true;
// Updating the distances of all the neighbouring vertices
for (int v=0; y < nodes: v++) {
if (visited vertex(v) && graph[u][v]! = 0 && (dist[u] + graph[u][v] < dist{v})) {
dist[v] = dist[u] + graph[u][v];
}
}
}
for (int i=0; i < dist.length; i++) {
System.out.println(String format("Distance from Vertex %s to Vertex %s is %s",
source, i, dist[i]));
}
}
//definding the medhod to find the minimum distance
privae static int find_min_distance(int[]dist, boolean[] visited_vertex) {
int minimum_distance = integer.Max_value;
int mininum_distance_vertex =-1;
for (int i=0; i<dist. length; i++){
if (visited vertex) && dist[i] < minimum_distance) {
minimum_distance = dist[i]}
minimum distance vertex=i;
}
}
retum minimum_distance_vertex;
}
// main function
public static void main(String[] args) {
// declaring the nodes of the graphs
int graph[][] = new int[][]{
{0,1,1,2,0,0,0},
{0,0,2,0,0,3,0},
{1,2,0,1,3,0,0},
{2,0,1,0,2,0,1},
{0,0,3,0,0,2,0},
{0,3,0,0,2,0,1},
{0,2,0,1,0,1,0}
};
//instantiating the DijkstraAlgorithm() class
DijkstraAlgorithm Test = new DijkstraAlgorithm())
// calling the dijkstraAlgorithm() method to find the shortest distance from the source
node to the destination node
Test.dijkstraAlgorithm(graph, 0)
}
}
Dijkstra Algorithm Python Code
Use the following code to implement Dijkstra’s Algorithm in Python.
File: DikstraAlgorithm.py
#Implementation of Dijkstra's Algorithm in Python
#importing the sys module
import sys
#declaring the list of nodes for the graph
nodes=[
[ 0, 0, 1, 0, 1, 0, 0]
[0, 0, 1, 0, 0, 1, 0],
[1, 1, 0, 1, 1, 0, 0
[1, 0, 1, 0, 0, 0, 1],
[0, 0, 1, 0, 0, 1, 0]
[0, 1, 0, 0, 1, 0, 1, ]
[ 0, 0, 0, 1, 0, 1, 0]
]
#declaring the list of edges for the graph
edges = [
[0,0,1,0,2,0,0],
[0, 0, 2, 0, 0, 3, 0],
[1,2,0,1,3,0,0],
[2, 0, 1, 0, 0, 0, 1],
[0,0,3,0,0,2, 0],
[0, 3, 0, 0, 2, 0, 1],
[0, 0, 0, 1, 0, 1,0]
]
# declaring the list of edges for the graph
edges=[
[ 0, 0, 1, 0, 2, 0, 0],
[ 0, 0, 2, 0, 0, 3, 0],
[ 1, 2, 0, 1, 3, 0, 0],
( 2, 0, 1, 0, 0, 0, 1, 1],
[ 0, 0, 3, 0, 0, 2, 0],
[0, 3, 0, 0, 2, 0, 1],
[ 0, 0, 0, 1, 0, 1, 0],
]
#defining the function to find which node is to be visited next
def toBevisited():
global visitedAndDistance
V=-10
for index in range(numberOfNodes);
If visitedAndDistance[index][0] == 0 and (v <0 or visitedAndDistance index][1]<=
visitedAndDistance[v][1]):
v=index
return v
#finding the number of nodes in the graph
numberOfNodes = len(nodes[0])
visitedAndDistance = [[0, 0]
for i in range(numberOfNodes - 1):
visitedAndDistance.append([0, sys.maxsize])
for node in range(numberOfNodes):
#finding the next node to be visited
toVisit = toBeVisited()
for neighborIndex in range(numberOfNodes)
#updating the new distances
if nodes to Visit][neighborIndex]== 1 and visitedAndDistance(neighborinbox[[0] ==0:
newDistance = visitedAndDistance toVisit][1] + edges[toVisit][neighborindex]
if visitedAndDistance neighborfndex][1] > newDistance:
visitedAndDistance[neighborIndex][1] = newDistance
visitedAndDistance(toVisit [0] =1
i=0
#printing the distance
for distance in visitedAndDistance:
print("Distance of", chr(ord("A") + i), "from source node", distance[1])
i=i+1
In-Demand Software Development Skills
Real-life Applications of Dijkstra’s Algorithm
Mentioned below are some real-world applications of Dijkstra’s Algorithm.
Mobile Network
Every transmission line in a mobile network consists of a bandwidth, ‘B’. The transmission line’s highest supported frequency is known as the bandwidth. In general, a line reduces a signal if the signal frequency is higher in that line. The amount of data transmitted over a line is measured as bandwidth.
Let’s imagine a city as a graph, where the graph nodes represent the switching station and the edges represent the transmission lines. The weight of the edges represents the bandwidth, or ‘B’. As a result, the mobile network can also be considered a type of shortest-distance problem that can be resolved using Dijkstra’s Algorithm.
Google Maps
We often try to find the distance between two cities interlinked with many routes or paths. We resort to Google Maps to show us the minimal distance. This is only possible because Dijkstra’s Algorithm aids the application in determining which portion of the path is shortest between two specified places.
Consider India as a network, with the cities and locations acting as the nodes and the routes connecting them as the edges. It is possible to figure out the shortest paths between any two cities or locations using Dijkstra’s Algorithm.
Flight Programme
Let’s consider that a person needs software to create a customer flight schedule. A database containing all flights and airports is available to the agent. The flights also consist of departure and arrival timings in addition to the origin airport, flight number and destination. Here, the agents can apply Dijkstra’s Algorithm to compute the earliest arrival time for the chosen destination from the original airport and the specified start time.
Pros and Cons of Dijkstra’s Algorithm
Dijkstra’s Algorithm comes with its own set of advantages and disadvantages.
Advantages
- Dijkstra’s Algorithm has a nearly linear space and time complexity.
- It can only be used with directed weighted graphs. This graph’s edges must be non-negative.
- Calculating the shortest distance from a single node to all other nodes is possible by using Dijkstra’s Algorithm. It is also possible to measure the shortest path from a source node to a destination node by ending the algorithm after we reach the shortest path for the destination node.
Disadvantages
- Dijkstra’s Algorithm cannot handle negative edges.
- This algorithm performs an obscured exploration. This takes up too much time during processing.
- Maintenance is required to keep track of the visited nodes.
- This algorithm cannot measure the exact shortest distance since it enters the acyclic graph.
Check Out upGrad’s Software Development Courses to upskill yourself.
Conclusion
Dijkstra’s Algorithm is useful for finding the shortest path between a source node and all other nodes in a graph. An in-depth knowledge of this algorithm is crucial for data scientists, along with the know-how to implement it in various programming languages. Enrol in an online data science course to understand it in detail and learn more about Dijkstra’s shortest path algorithm example and its real-world applications.
Frequently Asked Questions (FAQs)
1. What is the shortest path algorithm in data structure programme?
Dijkstra Algorithm in data structure finds the shortest path between a source node and all the other nodes in a graph. It uses a greedy approach to calculate the shortest path.
2. What is the time complexity of Dijkstra’s Algorithm?
The time complexity of Dijkstra’s Algorithm is O (E Log V), where V is the number of vertices or nodes, and E is the number of edges.
3. What is the difference between DFS and Dijkstra’s Algorithm?
While there is no guarantee that you will find the shortest path using DFS (Depth First Search), Dijkstra’s Algorithm does find the shortest path from a source node.
4. Which is better BFS or Dijkstra?
You can use BFS (Breadth First Search) to find the shortest path in undirected graphs, while Dijkstra helps you to find the shortest path in weighted graphs.
RELATED PROGRAMS