SlideShare une entreprise Scribd logo
1  sur  27
Working with
Dijkstra’s algorithm.
by Aditya Y. Bhargava
Save 42% off Grokking Algorithms
with code algrokking at
manning.com
Here’s a little info about Dijkstra’s algorithm:
You can use Dijkstra’s algorithm to find out how to go from start to
finish in the most expedient manner.
There are four steps to Dijkstra’s algorithm:
1. Find the “cheapest” node. This is the node you can get to in the least
amount of time.
2. Update the costs of the neighbors of this node. I’ll explain what I
mean by this shortly.
3. Repeat until you’ve done this for every node in the graph.
4. Calculate the final path.
Here’s a basic example:
Each segment has a travel time in minutes. We’ll use
Dijkstra’s algorithm to go from start to finish in the shortest
possible time.
Let’s go through
the 4 steps.
You’re standing at the start, wondering if you should go to
node A or node B. How long does it take to get to each node?
(6 mins to A and 2 mins to B – B is the cheapest node!)
Step 1 - find the
cheapest node:
Hey, wait a second… we just
found a shorter path to node
A! It used to take 6 minutes
to get to node A, but we can
get there in 5 mins by going
through B.
Step 2 – calculate how
long it takes to get to all of
node B’s neighbors by
following an edge from B:
Let’s recap what we just learned:
Since we found a shorter path for a neighbor of B, we’re going
to update its cost. In this case, we found:
• A shorter path to A (down from 6 minutes to 5 minutes)
• A shorter path to the finish (down from infinity to 7 minutes)
Now we go on to step 3: repeating steps 1 & 2 for all other
nodes, in this case that just leaves node A.
We’ve done node B already, so node A has the next smallest
time estimate.
Step 1 again - find
the cheapest
node:
Woo, it takes only 6 minutes to get to the finish now!
Step 2 again –
update the costs
for node A’s
neighbors:
We’ve run Dijkstra’s algorithm for every
node (you don’t need to run it for the
finish node). At this point, you know:
• It takes 2 minutes to get to node B.
• It takes 5 minutes to get to node A.
• It takes 6 minutes to get to the finish.
We just used Dijkstra’s
algorithm to calculate the
shortest path in a “weighted”
graph!
Step 4 – Calculate
the final path
(start to fin = 6):
*Hint* when you work with Dijkstra’s
algorithm, each edge in the graph has a
number associated with it. These are called
weights.
Let’s look at another example:
This is Rama.
Rama is trying to trade a music
book for a piano.
Luckily, Rama has friends who are willing to
trade some of their possessions.
“I’ll give you this poster for your book,” says Alex. “It’s a poster of
my favorite band, Destroyer. Or I’ll give you this rare LP of Rick
Astley for your book and $5 more.”
“Ooh, I’ve heard that LP has a really great song,” says Amy. “I’ll trade
you my guitar or drum set for the poster or the LP.”
“I’ve been meaning to get into guitar!” exclaims Beethoven. “Hey,
I’ll trade you my piano for either of Amy’s things.”
Perfect! With a little bit of
money, Rama can trade his
way from a piano book to a
real piano. Now he just needs
to figure out how to spend
the least amount of money to
make those trades. Let’s
graph out what he’s been
offered. The weights on the edges are the
amount of money he would have
to pay to make the trade.
Make a table of the cost for each node. The cost of a node is
how expensive it is to get to. You’ll keep updating this table as
the algorithm goes on.
Before we start, we
need this chart
(feel free to grab some
scratch paper and make
your own version).
To calculate the final path, you also need a parent column on
this table. We’ll see how this column works soon. For now,
let’s start the algorithm.
We also need a chart
like this one.
Let’s get started with
step one – finding the
cheapest node.
Trading for the poster
is the cheapest at $0.
Finding the cheapest node is
important, so make certain to take
your time on this step.
Next, were going to set the poster as the
new parent and figure out how long it takes
to get to its neighbors (the cost).
We now have two neighbors that we can reach from
the poster: the drums for $35; and the bass guitar
for $30.
Newly
unlocked
prices with
poster as
parent.
Now we have prices for the bass guitar and the drum set in the
table. Their value was set when we went through the poster, so
the poster gets set as their parent. That means, to get to the bass
guitar, we’re going to follow the edge from the poster, and the
same for the drums.
We’re going to repeat steps 1&2, finding
the next cheapest node and updating the
values of it’s neighbors.
Hey, now it’s cheaper to get to the drums and guitar
by following the edge from the LP. Let’s set the LP as
our new parent.
Repeat steps 1&2, again!
The bass guitar is our new cheapest node. And when
we update it’s neighbors, we get a price for the
piano - $40!
We finally have a price for the piano!
But it is the cheapest price? Let’s set the drums as
parent and see if we can’t get that piano for less.
Rama can get the piano more cheaply by trading
the drum set for the piano instead. So the cheapest
set of trades will cost Rama $35 total.
So far, we know that the shortest
path costs $35, but how do we
figure out the path? To start with,
look at the parent for piano.
The piano has drums as its parent. That means
Rama will trade the drums for the piano. So we
follow that edge back toward the book.
The drums have the LP as parent, so Rama
will trade the LP to get the drums.
Of course, this means that he’ll trade the book
for the LP. By following the parents backward,
we now have the complete path.
Here is the final path
Rama will need to take to
get the piano via the
shortest path (i.e. the
cheapest path). Thanks
Dijkstra!
Hopefully you’ve seen just how useful
Dijkstra’s algorithm can be.
Save 42% off Grokking Algorithms with code algrokking at
manning.com
Check out
some of
our other
great
titles:

Contenu connexe

En vedette

Analytic and strategic challenges of serious games
Analytic and strategic challenges of serious gamesAnalytic and strategic challenges of serious games
Analytic and strategic challenges of serious gamesDavid Gibson
 
Nutritional Therapists of Ireland, Health Impacts of Water Fluoridation May 2014
Nutritional Therapists of Ireland, Health Impacts of Water Fluoridation May 2014Nutritional Therapists of Ireland, Health Impacts of Water Fluoridation May 2014
Nutritional Therapists of Ireland, Health Impacts of Water Fluoridation May 2014Declan Waugh
 
Drupal y la programación defensiva (spanish version)
Drupal y la programación defensiva (spanish version)Drupal y la programación defensiva (spanish version)
Drupal y la programación defensiva (spanish version)Eduardo Telaya
 
La hosteleria 22 Marta Pedra Wines (2)
La hosteleria 22 Marta Pedra Wines (2)La hosteleria 22 Marta Pedra Wines (2)
La hosteleria 22 Marta Pedra Wines (2)Ocio Vital
 
Presentacio nova cultura de la salut Toni Barbarà
Presentacio nova cultura de la salut Toni BarbaràPresentacio nova cultura de la salut Toni Barbarà
Presentacio nova cultura de la salut Toni BarbaràDempeus Salut Pública
 
Relatório Caminhos para a produtividade - Indústria 4.0
Relatório Caminhos para a produtividade - Indústria 4.0Relatório Caminhos para a produtividade - Indústria 4.0
Relatório Caminhos para a produtividade - Indústria 4.0Fundação Dom Cabral - FDC
 
International Public Relations - Overview
International Public Relations - OverviewInternational Public Relations - Overview
International Public Relations - OverviewChip Lowe
 
Challenges in Extracting and Managing References
Challenges in Extracting and Managing ReferencesChallenges in Extracting and Managing References
Challenges in Extracting and Managing ReferencesGESIS
 
結晶と空間充填 #ロマ数ボーイズ
結晶と空間充填 #ロマ数ボーイズ結晶と空間充填 #ロマ数ボーイズ
結晶と空間充填 #ロマ数ボーイズhinge dearsip
 
Treatment of tb with sirturo
Treatment of tb with sirturoTreatment of tb with sirturo
Treatment of tb with sirturoKishore Chinna
 
Toma de muestra para analisis microbiologico de la leche y productos lacteos.
Toma de muestra para analisis microbiologico de la leche y productos lacteos.Toma de muestra para analisis microbiologico de la leche y productos lacteos.
Toma de muestra para analisis microbiologico de la leche y productos lacteos.UO
 

En vedette (12)

Analytic and strategic challenges of serious games
Analytic and strategic challenges of serious gamesAnalytic and strategic challenges of serious games
Analytic and strategic challenges of serious games
 
Nutritional Therapists of Ireland, Health Impacts of Water Fluoridation May 2014
Nutritional Therapists of Ireland, Health Impacts of Water Fluoridation May 2014Nutritional Therapists of Ireland, Health Impacts of Water Fluoridation May 2014
Nutritional Therapists of Ireland, Health Impacts of Water Fluoridation May 2014
 
Drupal y la programación defensiva (spanish version)
Drupal y la programación defensiva (spanish version)Drupal y la programación defensiva (spanish version)
Drupal y la programación defensiva (spanish version)
 
La hosteleria 22 Marta Pedra Wines (2)
La hosteleria 22 Marta Pedra Wines (2)La hosteleria 22 Marta Pedra Wines (2)
La hosteleria 22 Marta Pedra Wines (2)
 
Presentacio nova cultura de la salut Toni Barbarà
Presentacio nova cultura de la salut Toni BarbaràPresentacio nova cultura de la salut Toni Barbarà
Presentacio nova cultura de la salut Toni Barbarà
 
Relatório Caminhos para a produtividade - Indústria 4.0
Relatório Caminhos para a produtividade - Indústria 4.0Relatório Caminhos para a produtividade - Indústria 4.0
Relatório Caminhos para a produtividade - Indústria 4.0
 
The Winning Brand Formula
The Winning Brand Formula  The Winning Brand Formula
The Winning Brand Formula
 
International Public Relations - Overview
International Public Relations - OverviewInternational Public Relations - Overview
International Public Relations - Overview
 
Challenges in Extracting and Managing References
Challenges in Extracting and Managing ReferencesChallenges in Extracting and Managing References
Challenges in Extracting and Managing References
 
結晶と空間充填 #ロマ数ボーイズ
結晶と空間充填 #ロマ数ボーイズ結晶と空間充填 #ロマ数ボーイズ
結晶と空間充填 #ロマ数ボーイズ
 
Treatment of tb with sirturo
Treatment of tb with sirturoTreatment of tb with sirturo
Treatment of tb with sirturo
 
Toma de muestra para analisis microbiologico de la leche y productos lacteos.
Toma de muestra para analisis microbiologico de la leche y productos lacteos.Toma de muestra para analisis microbiologico de la leche y productos lacteos.
Toma de muestra para analisis microbiologico de la leche y productos lacteos.
 

Plus de Manning Publications

Privacy-Preserving Machine Learning: secure user data without sacrificing mod...
Privacy-Preserving Machine Learning: secure user data without sacrificing mod...Privacy-Preserving Machine Learning: secure user data without sacrificing mod...
Privacy-Preserving Machine Learning: secure user data without sacrificing mod...Manning Publications
 
Inside Deep Learning: theory and practice of modern deep learning
Inside Deep Learning: theory and practice of modern deep learningInside Deep Learning: theory and practice of modern deep learning
Inside Deep Learning: theory and practice of modern deep learningManning Publications
 
Data-Oriented Programming: making data a first-class citizen
Data-Oriented Programming: making data a first-class citizenData-Oriented Programming: making data a first-class citizen
Data-Oriented Programming: making data a first-class citizenManning Publications
 
Automated Machine Learning in Action
Automated Machine Learning in ActionAutomated Machine Learning in Action
Automated Machine Learning in ActionManning Publications
 
The Programmer's Brain: improve the way you learn and think about code
The Programmer's Brain: improve the way you learn and think about codeThe Programmer's Brain: improve the way you learn and think about code
The Programmer's Brain: improve the way you learn and think about codeManning Publications
 
Pipeline as Code: building a great deployment pipeline
Pipeline as Code: building a great deployment pipelinePipeline as Code: building a great deployment pipeline
Pipeline as Code: building a great deployment pipelineManning Publications
 
Tuning Up: keep your systems running smoothly
Tuning Up: keep your systems running smoothlyTuning Up: keep your systems running smoothly
Tuning Up: keep your systems running smoothlyManning Publications
 
Kubernetes Native Microservices with Quarkus and MicroProfile
Kubernetes Native Microservices with Quarkus and MicroProfileKubernetes Native Microservices with Quarkus and MicroProfile
Kubernetes Native Microservices with Quarkus and MicroProfileManning Publications
 
Crafting interactive troubleshooting guides and team documentation for your K...
Crafting interactive troubleshooting guides and team documentation for your K...Crafting interactive troubleshooting guides and team documentation for your K...
Crafting interactive troubleshooting guides and team documentation for your K...Manning Publications
 
Entity Framework Core in Action, Second Edtion
Entity Framework Core in Action, Second EdtionEntity Framework Core in Action, Second Edtion
Entity Framework Core in Action, Second EdtionManning Publications
 
Microservices in .NET Core, Second Edition
Microservices in .NET Core, Second EditionMicroservices in .NET Core, Second Edition
Microservices in .NET Core, Second EditionManning Publications
 
Kubernetes in Action, Second Edition
Kubernetes in Action, Second EditionKubernetes in Action, Second Edition
Kubernetes in Action, Second EditionManning Publications
 
Machine Learning with TensorFlow, Second Edition
Machine Learning with TensorFlow, Second EditionMachine Learning with TensorFlow, Second Edition
Machine Learning with TensorFlow, Second EditionManning Publications
 
Spring Microservices in Action, Second Edition
Spring Microservices in Action, Second EditionSpring Microservices in Action, Second Edition
Spring Microservices in Action, Second EditionManning Publications
 

Plus de Manning Publications (20)

Privacy-Preserving Machine Learning: secure user data without sacrificing mod...
Privacy-Preserving Machine Learning: secure user data without sacrificing mod...Privacy-Preserving Machine Learning: secure user data without sacrificing mod...
Privacy-Preserving Machine Learning: secure user data without sacrificing mod...
 
Inside Deep Learning: theory and practice of modern deep learning
Inside Deep Learning: theory and practice of modern deep learningInside Deep Learning: theory and practice of modern deep learning
Inside Deep Learning: theory and practice of modern deep learning
 
Data-Oriented Programming: making data a first-class citizen
Data-Oriented Programming: making data a first-class citizenData-Oriented Programming: making data a first-class citizen
Data-Oriented Programming: making data a first-class citizen
 
Automated Machine Learning in Action
Automated Machine Learning in ActionAutomated Machine Learning in Action
Automated Machine Learning in Action
 
The Programmer's Brain: improve the way you learn and think about code
The Programmer's Brain: improve the way you learn and think about codeThe Programmer's Brain: improve the way you learn and think about code
The Programmer's Brain: improve the way you learn and think about code
 
Pipeline as Code: building a great deployment pipeline
Pipeline as Code: building a great deployment pipelinePipeline as Code: building a great deployment pipeline
Pipeline as Code: building a great deployment pipeline
 
Tuning Up: keep your systems running smoothly
Tuning Up: keep your systems running smoothlyTuning Up: keep your systems running smoothly
Tuning Up: keep your systems running smoothly
 
Kubernetes Native Microservices with Quarkus and MicroProfile
Kubernetes Native Microservices with Quarkus and MicroProfileKubernetes Native Microservices with Quarkus and MicroProfile
Kubernetes Native Microservices with Quarkus and MicroProfile
 
Cloud Native Machine Learning
Cloud Native Machine Learning Cloud Native Machine Learning
Cloud Native Machine Learning
 
Spring in Action, Sixth Edition
Spring in Action, Sixth EditionSpring in Action, Sixth Edition
Spring in Action, Sixth Edition
 
Crafting interactive troubleshooting guides and team documentation for your K...
Crafting interactive troubleshooting guides and team documentation for your K...Crafting interactive troubleshooting guides and team documentation for your K...
Crafting interactive troubleshooting guides and team documentation for your K...
 
Entity Framework Core in Action, Second Edtion
Entity Framework Core in Action, Second EdtionEntity Framework Core in Action, Second Edtion
Entity Framework Core in Action, Second Edtion
 
Code like a Pro in C#
Code like a Pro in C#Code like a Pro in C#
Code like a Pro in C#
 
Microservices in .NET Core, Second Edition
Microservices in .NET Core, Second EditionMicroservices in .NET Core, Second Edition
Microservices in .NET Core, Second Edition
 
Kubernetes in Action, Second Edition
Kubernetes in Action, Second EditionKubernetes in Action, Second Edition
Kubernetes in Action, Second Edition
 
Core Kubernetes
Core KubernetesCore Kubernetes
Core Kubernetes
 
Machine Learning Bookcamp
Machine Learning BookcampMachine Learning Bookcamp
Machine Learning Bookcamp
 
Machine Learning with TensorFlow, Second Edition
Machine Learning with TensorFlow, Second EditionMachine Learning with TensorFlow, Second Edition
Machine Learning with TensorFlow, Second Edition
 
Spring Security in Action
Spring Security in ActionSpring Security in Action
Spring Security in Action
 
Spring Microservices in Action, Second Edition
Spring Microservices in Action, Second EditionSpring Microservices in Action, Second Edition
Spring Microservices in Action, Second Edition
 

Dernier

Unveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesUnveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesŁukasz Chruściel
 
What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...Technogeeks
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEEVICTOR MAESTRE RAMIREZ
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityNeo4j
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWave PLM
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio, Inc.
 
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...Cizo Technology Services
 
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...Angel Borroy López
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxTier1 app
 
Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)Ahmed Mater
 
Xen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdfXen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdfStefano Stabellini
 
Intelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmIntelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmSujith Sukumaran
 
SpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at RuntimeSpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at Runtimeandrehoraa
 
Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Velvetech LLC
 
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...confluent
 
How to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationHow to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationBradBedford3
 
Best Web Development Agency- Idiosys USA.pdf
Best Web Development Agency- Idiosys USA.pdfBest Web Development Agency- Idiosys USA.pdf
Best Web Development Agency- Idiosys USA.pdfIdiosysTechnologies1
 
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanySuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanyChristoph Pohl
 

Dernier (20)

2.pdf Ejercicios de programación competitiva
2.pdf Ejercicios de programación competitiva2.pdf Ejercicios de programación competitiva
2.pdf Ejercicios de programación competitiva
 
Unveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesUnveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New Features
 
What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEE
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered Sustainability
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need It
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
 
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
 
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
 
Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)
 
Xen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdfXen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdf
 
Intelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmIntelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalm
 
SpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at RuntimeSpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at Runtime
 
Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...
 
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort ServiceHot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
 
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
 
How to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationHow to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion Application
 
Best Web Development Agency- Idiosys USA.pdf
Best Web Development Agency- Idiosys USA.pdfBest Web Development Agency- Idiosys USA.pdf
Best Web Development Agency- Idiosys USA.pdf
 
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanySuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
 

Grokking Algorithms: working with Dijkstra's Algorithm

  • 1. Working with Dijkstra’s algorithm. by Aditya Y. Bhargava Save 42% off Grokking Algorithms with code algrokking at manning.com
  • 2. Here’s a little info about Dijkstra’s algorithm: You can use Dijkstra’s algorithm to find out how to go from start to finish in the most expedient manner. There are four steps to Dijkstra’s algorithm: 1. Find the “cheapest” node. This is the node you can get to in the least amount of time. 2. Update the costs of the neighbors of this node. I’ll explain what I mean by this shortly. 3. Repeat until you’ve done this for every node in the graph. 4. Calculate the final path.
  • 3. Here’s a basic example: Each segment has a travel time in minutes. We’ll use Dijkstra’s algorithm to go from start to finish in the shortest possible time.
  • 4. Let’s go through the 4 steps. You’re standing at the start, wondering if you should go to node A or node B. How long does it take to get to each node? (6 mins to A and 2 mins to B – B is the cheapest node!) Step 1 - find the cheapest node:
  • 5. Hey, wait a second… we just found a shorter path to node A! It used to take 6 minutes to get to node A, but we can get there in 5 mins by going through B. Step 2 – calculate how long it takes to get to all of node B’s neighbors by following an edge from B:
  • 6. Let’s recap what we just learned: Since we found a shorter path for a neighbor of B, we’re going to update its cost. In this case, we found: • A shorter path to A (down from 6 minutes to 5 minutes) • A shorter path to the finish (down from infinity to 7 minutes) Now we go on to step 3: repeating steps 1 & 2 for all other nodes, in this case that just leaves node A.
  • 7. We’ve done node B already, so node A has the next smallest time estimate. Step 1 again - find the cheapest node:
  • 8. Woo, it takes only 6 minutes to get to the finish now! Step 2 again – update the costs for node A’s neighbors:
  • 9. We’ve run Dijkstra’s algorithm for every node (you don’t need to run it for the finish node). At this point, you know: • It takes 2 minutes to get to node B. • It takes 5 minutes to get to node A. • It takes 6 minutes to get to the finish.
  • 10. We just used Dijkstra’s algorithm to calculate the shortest path in a “weighted” graph! Step 4 – Calculate the final path (start to fin = 6): *Hint* when you work with Dijkstra’s algorithm, each edge in the graph has a number associated with it. These are called weights.
  • 11. Let’s look at another example: This is Rama. Rama is trying to trade a music book for a piano.
  • 12. Luckily, Rama has friends who are willing to trade some of their possessions. “I’ll give you this poster for your book,” says Alex. “It’s a poster of my favorite band, Destroyer. Or I’ll give you this rare LP of Rick Astley for your book and $5 more.” “Ooh, I’ve heard that LP has a really great song,” says Amy. “I’ll trade you my guitar or drum set for the poster or the LP.” “I’ve been meaning to get into guitar!” exclaims Beethoven. “Hey, I’ll trade you my piano for either of Amy’s things.”
  • 13. Perfect! With a little bit of money, Rama can trade his way from a piano book to a real piano. Now he just needs to figure out how to spend the least amount of money to make those trades. Let’s graph out what he’s been offered. The weights on the edges are the amount of money he would have to pay to make the trade.
  • 14. Make a table of the cost for each node. The cost of a node is how expensive it is to get to. You’ll keep updating this table as the algorithm goes on. Before we start, we need this chart (feel free to grab some scratch paper and make your own version).
  • 15. To calculate the final path, you also need a parent column on this table. We’ll see how this column works soon. For now, let’s start the algorithm. We also need a chart like this one.
  • 16. Let’s get started with step one – finding the cheapest node. Trading for the poster is the cheapest at $0. Finding the cheapest node is important, so make certain to take your time on this step.
  • 17. Next, were going to set the poster as the new parent and figure out how long it takes to get to its neighbors (the cost). We now have two neighbors that we can reach from the poster: the drums for $35; and the bass guitar for $30. Newly unlocked prices with poster as parent.
  • 18. Now we have prices for the bass guitar and the drum set in the table. Their value was set when we went through the poster, so the poster gets set as their parent. That means, to get to the bass guitar, we’re going to follow the edge from the poster, and the same for the drums.
  • 19. We’re going to repeat steps 1&2, finding the next cheapest node and updating the values of it’s neighbors. Hey, now it’s cheaper to get to the drums and guitar by following the edge from the LP. Let’s set the LP as our new parent.
  • 20. Repeat steps 1&2, again! The bass guitar is our new cheapest node. And when we update it’s neighbors, we get a price for the piano - $40!
  • 21. We finally have a price for the piano! But it is the cheapest price? Let’s set the drums as parent and see if we can’t get that piano for less.
  • 22. Rama can get the piano more cheaply by trading the drum set for the piano instead. So the cheapest set of trades will cost Rama $35 total. So far, we know that the shortest path costs $35, but how do we figure out the path? To start with, look at the parent for piano.
  • 23. The piano has drums as its parent. That means Rama will trade the drums for the piano. So we follow that edge back toward the book.
  • 24. The drums have the LP as parent, so Rama will trade the LP to get the drums.
  • 25. Of course, this means that he’ll trade the book for the LP. By following the parents backward, we now have the complete path.
  • 26. Here is the final path Rama will need to take to get the piano via the shortest path (i.e. the cheapest path). Thanks Dijkstra!
  • 27. Hopefully you’ve seen just how useful Dijkstra’s algorithm can be. Save 42% off Grokking Algorithms with code algrokking at manning.com Check out some of our other great titles: