Utilizamos seu perfil e dados de atividades no LinkedIn para personalizar e exibir anúncios mais relevantes. Altere suas preferências de anúncios quando desejar.
Próximos SlideShares
Carregando em…5
×

# Grokking Algorithms: working with Dijkstra's Algorithm

4.466 visualizações

Grokking Algorithms is a fully illustrated, friendly guide that teaches you how to apply common algorithms to the practical problems you face every day as a programmer.

Save 42% off Grokking Algorithms with code algrokking at: https://www.manning.com/books/grokking-algorithms

• Full Name
Comment goes here.

Are you sure you want to Yes No
• Seja o primeiro a comentar

### Grokking Algorithms: working with Dijkstra's Algorithm

1. 1. Working with Dijkstra’s algorithm. by Aditya Y. Bhargava Save 42% off Grokking Algorithms with code algrokking at manning.com
2. 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. 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. 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. 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. 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. 7. We’ve done node B already, so node A has the next smallest time estimate. Step 1 again - find the cheapest node:
8. 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. 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. 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. 11. Let’s look at another example: This is Rama. Rama is trying to trade a music book for a piano.
12. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 24. The drums have the LP as parent, so Rama will trade the LP to get the drums.
25. 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. 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. 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: