0% found this document useful (0 votes)
14 views48 pages

15 Dijkstra

Uploaded by

May Dehayni
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views48 pages

15 Dijkstra

Uploaded by

May Dehayni
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 48

Lecture 15: Shortest CSE 373: Data Structures

Paths and Algorithms

CSE 373 19 SU - ROBBIE WEBER 1


Roadmap
- Graphs examples, shortest paths for unweighted graphs
- using BFS to find the shortest paths
- shortest paths for weighted graphs
- Idea 1: using BFS directly
- Idea 2: modifying the graph
- Idea 3: modifying the order of visiting nodes
- examples
- runtime if time?

CSE 373 SP 18 - KASEY CHAMPION 2


Shortest Paths
How does Google Maps figure out this is the fastest way to get from Kane Hall
to the CS building?

CSE 373 19 SU - ROBBIE WEBER 3


Representing Maps as Graphs
How do we represent a map as a graph? What are the vertices and edges?

CSE 373 19 SU - ROBBIE WEBER 4


Representing Maps as Graphs

R
S
H

D
P

CSE 373 19 SU - ROBBIE WEBER 5


Shortest Path problem (unweighted
graph)
 For the graph on the right, find the shortest
d
path (the path that has the fewest
number of edges) between the a node and b
the g node. Describe the path by describing
each edge (i.e. (a, b) edge).
s e f
 What’s the answer? How did we get that as a
humans? How do we want to do it c
comprehensively defined in an algorithm?
g

h
Shortest Path problem (unweighted
graph)
What’s the shortest path from a to a?
- Well….we’re already there.
d
What’s the shortest path from a to b or h?
- Just go on the edge from 0
b
From a to d or c or e?
- Can’t get there directly from a, if we want a length 2 path,
have to go through b or h. s e f
a
From a to f?
c
- Can’t get there directly from a, if we want a length 3 path, have to go through e.

g
big idea for solving shortest paths: If we have all the nodes at distance k away
from the source, then we can check all the outgoing edges from those nodes and get
to all the nodes at distance k + 1 (if we haven’t seen these nodes at k +1 distance
before then we’re just now seeing the shortest path to them)
h
As long as we have all the current vertices at a given distance, we can find the next
distance (by traveling to all the neighbors) and the next distance and the next
distance… until we finally find our target vertex and can stop.

CSE 373 19 SU - ROBBIE WEBER 7


Shortest Path problem (unweighted
graph) key idea
Do we already know an algorithm that can help us get all the nodes at a given
level and help us keep going through the graph level by level?
Yes! BFS! Let’s modify it to fit our needs.

perimeter.add(start);
discovered.add(start);
Changes from traversal BFS: start’s distance = 0;
- Every node now will have an while (!perimeter.isEmpty()) {
Vertex from = perimeter.remove();
associated distance (for convenience)
- Every node V now will have an for (E edge : graph.outgoingEdgesFrom(from)) {
Vertex to = edge.to();
associated predecessor edge that is
if (!discovered.contains(to)) {
the edge that connects V on the to’s distance = from.distance + 1;
shortest path from S to V. The edges to’s predecessorEdge = edge;
that each of the nodes store are the perimeter.add(to);
final result. discovered.add(to)
}
}
} CSE 373 19 SU - ROBBIE WEBER 8
Shortest Path problem d
b
Use BFS to find shortest paths in this graph.
s e f
perimeter.add(start);
a
discovered.add(start); c
start’s distance = 0;
while (!perimeter.isEmpty()) { g
Vertex from = perimeter.remove();
for (E edge : graph.outgoingEdgesFrom(from)) {
Vertex to = edge.to();
if (!discovered.contains(to)) { h
In English:
to’s distance = from.distance + 1;
to’s predecessorEdge = edge;
- starting from the start vertex as the current
perimeter.add(to);
discovered.add(to) node:
} - look at all your undiscovered neighbors and
} record them as distance + 1, and keep track
} of the edge that led to them. Add them to a
queue to be processed
- repeat until we traverse all that can
CSE 373 be- ROBBIE WEBER
19 SU
Shortest Path problem d
b

Use BFS to find shortest paths in this graph.


s e f
a
perimeter.add(start);
c t
discovered.add(start);
start’s distance = 0;
while (!perimeter.isEmpty()) {
g
Vertex from = perimeter.remove();
for (E edge : graph.outgoingEdgesFrom(from)) {
Vertex to = edge.to();
if (!discovered.contains(to)) { If trying to recall the best path from a h
to f:
to’s distance = from.distance + 1; f’s predecessor edge is (f, e)
to’s predecessorEdge = edge; e’s predecessor edge is (e, h)
perimeter.add(to); h’s predecessor edge is (a, h)
discovered.add(to) a was the start vertex
}
}
Note: this BFS modification stores these edges
}
individually, but there’s extra work to figure out a
specific path from a start / target CSE 373 19 SU - ROBBIE WEBER 10
Map<V, E> bfsFindShortestPathsEdges(G graph, V start) {
// stores the edge `E` that connects `V` in the shortest path from `start` to V
Map<V, E> edgeToV = empty map

// stores the shortest path length from `start` to `V`


Map<V, Double> distToV = empty map

Queue<V> perimeter = empty queue


Set<V> discovered = empty set

// setting up the shortest distance from start to start is just 0 with d


// no edge leading to it
edgeTo.put(start, null); b
distTo.put(start, 0.0);

perimeter.add(start);

while (!perimeter.isEmpty()) { s e f
V from = perimeter.remove(); a
for (E e : graph.outgoingEdgesFrom(from)) {
V to = e.to(); c
if (!discovered.contains(to)) {
edgeTo.put(to, e);
distTo.put(to, distTo(from) + 1);
g
perimeter.add(to);
discovered.add(to)
}
}
} h
return edgeToV;
}
d
b
What about the target vertex?
Shortest Path Problem s e f
a
Given: a directed graph G and vertices
c
s,t
Find: the shortest path from s to t. g

BFS didn’t mention a target vertex… h


It actually finds the distance from s to every other vertex since we needed
to traverse the graph anyways. The resulting edges from our BFS shortest
paths algorithm are called the shortest path tree (SPT: the set of all edges
that are used in the shortest paths from a particular start vertex to every
other vertex – see red edges above)

Both BFS modified to find the shortest paths and Dijkstra’s algorithm need to
start computing a shortest path tree in order to find the target.

But if you only care about one target, you can sometimes stop early (in
CSE 373 19 SU - ROBBIE WEBER 12
BFS Shortest Path Summary
- BFS works to find the shortest path summary because BFS traverses the graph
level by level outwards from the start -- because we’re making sure we look at all
the neighbors of all the vertices on the current level, it means that the first time
that we see some vertex u means that we’ve found the shortest path to u. There’s
no way there’s a shorter path because of how comprehensively we’re searching the
graph. (If there were a shorter path, it should have been found at an earlier level!)
slightly more concrete example:
- If you start at level 0, there’s only the start node, and you’ve definitely found the shortest path to that by default (0 edges)
- If you look at the neighbors of the start node who are all at 1 edge/distance away, you’ve definitely found the shortest path to
all of those since they’re just 1 edge length away and it’s not like they could be 0 away.
- If you look at all the neighbors of the nodes who were at 1 edge/distance away, you’re looking at all the nodes who are 2
distance away (when you ignore previously discovered nodes). Since you made sure we were comprehensive about finding all
the nodes at 0 and 1 distance away, the nodes we’re seeing for the first time here must be have 2 as the shortest possible
distance.

- BFS shortest paths keeps track of the actual paths by just keeping track of for
every vertex V, the predecessorEdge that was used to attach V in the SPT. Which
means to trace back a full path you have to loop through all of the
predecessorEdges to go back to the root of the SPT/start vertex.
CSE 373 SP 18 - KASEY CHAMPION 13
BFS Shortest Path Summary
another of way rephrasing this is through invariants:
- because we add vertices to the queue in level order and have the guarantee
that the information in the

when a vertex is added to the queue with its predecessorEdge and distance
recorded, we’ve guaranteed to have found the shortest path /distance to that
vertex

CSE 373 SP 18 - KASEY CHAMPION 14


Questions?
- Shortest path problem in general
- BFS to solve and traverse in level order
- solving it like this produces a SPT
- to recover an actual path have to follow the
predecessor edges on the SPT

CSE 373 SP 18 - KASEY CHAMPION 15


Roadmap
- Graphs examples, shortest paths for unweighted graphs
- using BFS to find the shortest paths
- shortest paths for weighted graphs
- Idea 1: using BFS directly
- Idea 2: modifying the graph
- Idea 3: modifying the order of visiting nodes
- examples
- runtime if time?

CSE 373 SP 18 - KASEY CHAMPION 16


Weighted Graphs
Each edge should represent the “time” or “distance” it takes to travel from
one vertex to another.
Sometimes those aren’t uniform, so we put a weight on each edge to record
that number.

The length of a path in a weighted graph is the sum of the weights along that
path (instead of just counting the # of edges).

We’ll assume all of the weights are positive


- For Google Maps that definitely makes sense.
- Sometimes negative weights make sense. Today’s algorithm doesn’t
work for those graphs
- There are other algorithms that do work.
CSE 373 19 SU - ROBBIE WEBER 17
Weighted Graphs: Take 1
BFS works if the graph is unweighted.
Maybe it just works for weighted graphs too?

1
w x 1
1
s u v t
20 1 1

CSE 373 19 SU - ROBBIE WEBER


Weighted Graphs: Take 1
BFS works if the graph is unweighted. Maybe it just works for weighted graphs
too?

1 1 ∞
2
w x 1
1
u v t
s
1 1
0 20 ∞
20
3 ∞
21 ∞
22

What went wrong? When we found a shorter path from s to u, we needed to


update the distance to v (and anything whose shortest path went through u)
but BFS doesn’t do that.
CSE 373 19 SU - ROBBIE WEBER 19
Weighted Graphs: Take 2
Reduction (informally)
Using an algorithm for Problem B to solve
Problem A.
You already do this all the time.

Any time you use a library, you’re reducing your problem to


the one the library solves.
Can we reduce finding shortest paths on weighted graphs to
finding them on unweighted graphs?

CSE 373 19 SU - ROBBIE WEBER


Weighted Graphs: Take 2
Given a weighted graph, how do we turn it into an
unweighted one without messing up the path lengths?

CSE 373 19 SU - ROBBIE WEBER


Weighted Graphs: A Reduction

u
2 u 1
2 s Transform Input t
s t
v
1 v 2 u
Unweighted Shortest
s Paths t 2
v
2 u 1
2 Outputt 2
sTransform
1 v 2
CSE 373 19 SU - ROBBIE WEBER
Weighted Graphs: A Reduction
What is the running time Does our reduction even
of our reduction on this work on this graph?
graph?
5000 u 15 0.5 u 3
s 200 0 t s 𝜋 t
1 v 5000 1 v 500
0
BFS relies on traversing the vertices and Ummm….
edges, so if there are suddenly 5000x more
of each the runtime will get a lot worse.
tl;dr: If your graph’s weights are all small positive integers,
this reduction might work great.
Otherwise we probably need a new idea.
CSE 373 19 SU - ROBBIE WEBER
Weighted Graphs: Take 3
So we can’t just do a reduction.
Instead figure out why BFS worked in the unweighted case,
try to make the same thing happen in the weighted case.
How did we avoid this problem:

1 1 2
w x 1
1
u v t
s
1 1
0 20 3 21 22

CSE 373 19 SU - ROBBIE WEBER


Weighted Graphs: TakeInguarantee
3the unweighted case, we have this
that the way we traverse
the graph level-by-level, we’re
always finding the shortest distance
w x to each vertex along the way.

u v t
s

When we tried to do the same BFS on the


1 weighted graph earlier, we weren’t taking the
edge weights into account and we ended up
1 processing u and updating its out neighbors
w x before we knew u’s true shortest path / distance.
1
So it seems we did things out of order and should
have processed u after processing x (and w).
u v t
s
1 1
6

Idea: what if we copy the level-by-level idea but instead traverse distance-by-distance?
CSE 373 19 SU - ROBBIE WEBER
Weighted Graphs: Take 3 -Visiting nodes in
distance-order (should seem similar to BFS still)
1
1
w x
1

u v t
s
1 1
6
- One way to think about our new algorithm: imagine that every edge weight represents the distance it takes to
traverse that edge, and that we’ll simulate the order of traversal by trying to explore all of our outgoing edges at
the same time but with respect to the edge weight distances.
- Say we start at search at s and want to traverse to our neighbors 1 distance/time away: since we’re thinking of
this process traversing in all possible directions, how far do we get? Well S  W is only distance 1, so we actually
get to W. The S U edge that we know about is distance 6, so even though we started traversing it, we only get
1/6 of the way through that edge.
- Say another unit of time passes in our constant traversal and we traverse 1 more distance in all the directions,
and now the upper path has traversed WX (total distance from S is 2), and meanwhile S  U is only 2/6 done.
- Say another unit of time passes and we get to U through XU (total dist from S is 3), and SU is 3/6 done.
This order of processing nodes guarantees that when we finally reach a node U (with the constant rate of travel
idea) we’ve guaranteed we found the shortest path to it (just like BFS if there were a shorter path, we would’ve
gotten here sooner since we’re exploring all the paths simultaneously).

CSE 373 SP 18 - KASEY CHAMPION 26


Weighted Graphs: Take 3
Goal: Process the vertices in order of distance from s (instead of level order)
Idea:
Have a set of vertices that are “known”
- (we know at least one path from s to them).
Record an estimated distance
- (the best way we know to get to each vertex).
If we process only the vertex closest in estimated distance, we won’t ever find a
shorter path to a processed vertex. This takes a jump from the previous way of
distance-by-distance, but is the same high-level idea.
For example, there are some cases in the distance-by-distance approach where you
could say we’d be 3/7 of the way through one edge and 3/9 way through another
edge. Instead of manually stepping through +1 each time, this is like cutting to the
answer and just realizing that the 7 edge would finish before the 9 (we should process
the edge with weight 7 first) if they both started at the same time.
- This statement is the key to proving correctness.

CSE 373 19 SU - ROBBIE WEBER


Questions?
- weighted graph shortest paths
- using BFS directly
- modifying the graph
- traversing in distance-order

CSE 373 SP 18 - KASEY CHAMPION 28


Dijkstra’s algorithm (pseudocode +
English)
Dijkstra(Graph G, Vertex source) - propose all the estimated distances to
initialize distances to all nodes is infinity, except for the start
mark source as distance 0 which is 0
mark all vertices unprocessed - start at your start vertex
while(there are unprocessed vertices){
let u be the closest unprocessed - for the current vertex, look at all of
vertex the outgoing neighbors/their edges. If
foreach(edge (u,v) leaving u){ the distance to the current node + that
if(u’s dist+weight(u,v) < edge weight is smaller than the
v’s dist){ proposed estimated distance for that
v’s dist =
neighbor, relax the neighbor node
u.dist+weight(u,v) (update the proposed estimated
v’s predecessor =
distance and predecessor edge).
(u,v) - update the current vertex to be the
} vertex w the next smallest estimated
} distance that hasn’t been processed
mark u as processed
CSE 373 SP 18 - KASEY CHAMPION 29
}
Dijkstra’s Algorithm
Vert Distan Predeces Process
ex ce sor ed
Dijkstra(Graph G, Vertex source)
initialize distances to s
mark source as distance 0
mark all vertices unprocessed w
while(there are unprocessed vertices){ x
let u be the closest unprocessed
vertex u
foreach(edge (u,v) leaving u){
v
if(u’s dist+weight(u,v) <
v’s dist){ t
v’s dist =
1
u.dist+weight(u,v)
w x 1
v’s predecessor = 1
(u,v)
s u v t
}
} 20 1 1
mark u as processed
} CSE 373 19 SU - ROBBIE WEBER
Dijkstra’s Algorithm Vert Distan Predeces Process
ex ce sor ed
Dijkstra(Graph G, Vertex source)
initialize distances to
s 0 -- Yes
mark source as distance 0 w 1 (s,w ) Yes
mark all vertices unprocessed
while(there are unprocessed vertices){ x 2 (w, x) Yes
let u be the closest unprocessed u 20 3 (s,u) (x, Yes
vertex
u)
foreach(edge (u,v) leaving u){
if(u’s dist+weight(u,v) < v 4 (u, v) Yes
v’s dist){
v’s dist = 1t 5 (v, t) Yes
w x 1
u.dist+weight(u,v) 1
v’s predecessor =
s u v t
(u,v)
} 2 1 1
} 0
mark u as processed
} CSE 373 19 SU - ROBBIE WEBER
Predeces Processe
Dijkstra’s Run Through Vertex Distance
sor d
S
C
Pseudocode
B
Dijkstra(Graph G, Vertex source)
initialize distances to T
mark all vertices unprocessed
mark source as distance 0 E
while(there are unprocessed vertices){
let u be the closest unprocessed vertex
for each(edge (u,v) leaving u){
if(u’s dist+weight(u,v) < v’s dist){
v’s dist = u.dist+weight(u,v)
v’s predecessor = (u,v)
}
}
mark u as processed
}

CSE 373 19 SU - ROBBIE WEBER 32


Predeces Processe
Dijkstra’s Run Through Vertex Distance
sor d
S 0 No
C ∞ No
Pseudocode
B ∞ No
Dijkstra(Graph G, Vertex source)
initialize distances to T ∞ No
mark all vertices unprocessed
mark source as distance 0 E ∞ No
while(there are unprocessed vertices){
let u be the closest unprocessed vertex
for each(edge (u,v) leaving u){
if(u’s dist+weight(u,v) < v’s dist){
v’s dist = u.dist+weight(u,v)
v’s predecessor = (u,v)
}
}
mark u as processed
}

CSE 373 19 SU - ROBBIE WEBER 33


Predeces Processe
Dijkstra’s Run Through Vertex Distance
sor d
S 0 -- No
C 6 S No
Pseudocode
B 1 S No
Dijkstra(Graph G, Vertex source)
initialize distances to T ∞ No
mark all vertices unprocessed
mark source as distance 0 E ∞ No
while(there are unprocessed vertices){
let u be the closest unprocessed vertex
for each(edge (u,v) leaving u){
if(u’s dist+weight(u,v) < v’s dist){
v’s dist = u.dist+weight(u,v)
v’s predecessor = (u,v)
}
}
mark u as processed
}

CSE 373 19 SU - ROBBIE WEBER 34


Predeces Processe
Dijkstra’s Run Through Vertex Distance
sor d
S 0 -- Yes
C 6 S No
Pseudocode
B 1 S No
Dijkstra(Graph G, Vertex source)
initialize distances to T ∞ No
mark all vertices unprocessed
mark source as distance 0 E ∞ No
while(there are unprocessed vertices){
let u be the closest unprocessed vertex
for each(edge (u,v) leaving u){
if(u’s dist+weight(u,v) < v’s dist){
v’s dist = u.dist+weight(u,v)
v’s predecessor = (u,v)
}
}
mark u as processed
}

CSE 373 19 SU - ROBBIE WEBER 35


Predeces Processe
Dijkstra’s Run Through Vertex Distance
sor d
S 0 -- Yes
C 6 S No
Pseudocode
B 1 S Yes
Dijkstra(Graph G, Vertex source)
initialize distances to T 6 B No
mark all vertices unprocessed
mark source as distance 0 E 2 B No
while(there are unprocessed vertices){
let u be the closest unprocessed vertex
for each(edge (u,v) leaving u){
if(u’s dist+weight(u,v) < v’s dist){
v’s dist = u.dist+weight(u,v)
v’s predecessor = (u,v)
}
}
mark u as processed
}

CSE 373 19 SU - ROBBIE WEBER 36


Predeces Processe
Dijkstra’s Run Through Vertex Distance
sor d
S 0 -- Yes
C 6 S No
Pseudocode
B 1 S Yes
Dijkstra(Graph G, Vertex source)
initialize distances to T 63 E No
mark all vertices unprocessed
mark source as distance 0 E 2 B Yes
while(there are unprocessed vertices){
let u be the closest unprocessed vertex
for each(edge (u,v) leaving u){
if(u’s dist+weight(u,v) < v’s dist){
v’s dist = u.dist+weight(u,v)
v’s predecessor = (u,v)
}
}
mark u as processed
}

CSE 373 19 SU - ROBBIE WEBER 37


Predeces Processe
Dijkstra’s Run Through Vertex Distance
sor d
S 0 -- Yes
C 6 S No
Pseudocode
B 1 S Yes
Dijkstra(Graph G, Vertex source)
initialize distances to T 63 E Yes
mark all vertices unprocessed
mark source as distance 0 E 2 B Yes
while(there are unprocessed vertices){
let u be the closest unprocessed vertex
for each(edge (u,v) leaving u){
if(u’s dist+weight(u,v) < v’s dist){
v’s dist = u.dist+weight(u,v)
v’s predecessor = (u,v)
}
}
mark u as processed
}

CSE 373 19 SU - ROBBIE WEBER 38


Dijkstra’s Pseuodocode
Dijkstra(Graph G, Vertex source)
initialize distances to Min Priority Queue ADT
mark source as distance 0
state
mark all vertices unprocessed
Set of comparable
while(there are unprocessed vertices){ values - Ordered by
let u be the closest unprocessed vertex Huh? “priority”
behavior
foreach(edge (u,v) leaving u){
peek() – find the element
if(u’s dist+weight(u,v) < v’s dist){ with the smallest priority
v.dist = u.dist+weight(u,v) insert(value) – add new
v.predecessor = (u,v) element to collection
} removeMin() – returns and
} removes element with the
smallest priority
mark u as processed
}

CSE 373 19 SU - ROBBIE WEBER 39


Dijkstra’s Pseuodocode
Dijkstra(Graph G, Vertex source)
initialize distances to Min Priority Queue ADT
mark source as distance 0
state
mark all vertices unprocessed
Set of comparable
initialize MPQ as a Min Priority Queue, add source values - Ordered by
while(there are unprocessed vertices){ How? “priority”
behavior
u = MPQ.removeMin();
peek() – find the element
foreach(edge (u,v) leaving u){ with the smallest priority
if(u’s dist+weight(u,v) < v’s dist){ insert(value) – add new
v.dist = u.dist+weight(u,v) element to collection
v.predecessor = (u,v) removeMin() – returns and
} removes element with the
smallest priority
}
mark u as processed
} CSE 373 19 SU - ROBBIE WEBER 40
What are the high-level differences between
using BFS and Dijkstra’s algorithm?
findShortestPathsTree(G unweightedGraph, V start) { findShortestPathsTree(G weightedGraph, V start) {
Map<V, E> edgeToV = empty map Map<V, E> edgeToV = empty map
Map<V, Double> distToV = empty map Map<V, Double> distToV = empty map

Queue<V> perimeter = empty queue


Set<V> discovered = empty set PQ<V> orderedPerimeter = empty pq

initialize all distTo's to ∞ so the best paths


can be updated if any path is found to that vertex
perimeter.add(start);
distTo.put(start, 0.0); orderedPerimeter.add(start, 0);
distTo.put(start, 0.0);
while (!perimeter.isEmpty()) {
while (!orderedPerimeter.isEmpty()) {
V from = perimeter.remove();
V from = orderedPerimeter.removeMin();
for (E e : unweightedGraph.outgoingEdgesFrom(from)) {
for (E e : weightedGraph.outgoingEdgesFrom(from)) {
V to = e.to(); V to = e.to();
if (!discovered.contains(to)) { double oldDist = distTo.get(to);
edgeTo.put(to, e); double newDist = distTo.get(from) + e.weight();
distTo.put(to, distTo(from) + 1); if (newDist < oldDist) {
perimeter.add(to); edgeToV.put(to, e);
discovered.add(to) distToV.put(to, newDist);
} if (pq contain to) {
} orderedPerimeter.changePriority(to, newDist);
} } else {
} orderedPerimeter.add(to, newDist);
}
}
}
}
}

CSE 373 SP 18 - KASEY CHAMPION 41


What are the high-level differences between
using BFS and Dijkstra’s algorithm?
BFS iterates in level order, ordering in-between levels is not important by
default. So BFS uses a Queue as it’s internal data structure to keep track of
the ordering.
Dijkstra’s iterates in priority order, prioritizing processing nodes with the next
smallest estimated distance (so that we get that guarantee that we’re looking
at correct information). So Dijkstra’s uses a PriorityQueue as it’s internal data
structure to keep track of the ordering.

Overall they’re really similar and Dijkstra’s just has a few more steps than BFS,
so if you’re confused, start with understanding BFS shortest paths and then
after you feel comfortable with that, tackle practicing / understanding
Dijktra’s.

CSE 373 SP 18 - KASEY CHAMPION 42


Questions?

CSE 373 SP 18 - KASEY CHAMPION 43


BFS/DFS runtime
All of the data structure operations (remove, add, contains)
perimeter.add(start); are all constant runtime and so are getting values out of the
discovered.add(start); graph (neighbors, distance, etc.).
start’s distance = 0; So the main runtime is going to come from just how much
while (!perimeter.isEmpty()) { we’re looping / how many things we’re looking at. Since we
know that we could loop through all vertices, we know it’s
Vertex from = perimeter.remove(); going to take at least n time (where n is the number of
for (E edge : graph.outgoingEdgesFrom(from)) { nodes)
Vertex to = edge.to(); And for each of those vertices, we loop through all of it’s
if (!discovered.contains(to)) { edges. Caution: m represents the number of edges in the
whole graph, so we can’t just use n * m for our runtime,
to’s distance = from.distance + 1; because each vertex only looks at its own neighbors, not the
to’s predecessorEdge = edge; entire edge list for the whole graph.
perimeter.add(to); It turns out the way to model this standard traversal is n +
discovered.add(to) m runtime (in the worst case if the whole graph is actually
explored). This is because we look at every vertex once and
} we actually look at every unique edge twice (from the
} perspectives of the 2 different vertices attached to the edge).
} Another way to think about this is that the inner for each loop
actually runs in m/n time, where m/n represents the average
number of edges per node. If you multiply this happening
actually n times, then you get that the code inside the inner
for loop runs m times. (And the code inside the while loop and
outside of the for loop like the Queue.remove runs n times).

CSE 373 SP 18 - KASEY CHAMPION 44


Just like when we analyzed

Dijkstra’s Runtime BFS, don’t just work inside


out; try to figure out how
many times each line will be
Dijkstra(Graph G, Vertex source) executed.
for (Vertex v : G.getVertices()) { v.dist = INFINITY; }
G.getVertex(source).dist = 0;
initialize MPQ as a Min Priority Queue, add source
while(MPQ is not empty){
u = MPQ.removeMin();+logV This actually doesn’t run
for (Edge e : u.getEdges(u)){ times for every iteration of
oldDist = v.dist; newDist = u.dist+weight(u,v)
the outer loop. It actually
will run times in total; if
if(newDist < oldDist){
every vertex is only
v.dist = newDist removed from the priority
v.predecessor = u queue (processed) once,
if(oldDist == INFINITY) { MPQ.insert(v) }+logV
then we examine each edge
once. Each line inside this
else { MPQ.updatePriority(v, newDist) }
foreach gets multiplied by a
} single E instead of E * V.
} Tight O Bound = O(n log
n + m log n)
CSE 373 19 SU - ROBBIE WEBER 45
}
Dijkstra’s Wrap-up
The details of the implementation depend on what data structures you have
available.
Your implementation in the programming project will be different in a few
spots.

Our running time is i.e.

CSE 373 SU 19 - ROBBIE WEBER 46


CSE 373 SU 19 - ROBBIE WEBER 47
Dijkstra’s Wrap-up
The details of the implementation depend on what data structures you have
available.
Your implementation in the programming project will be different in a few spots.

Our running time is i.e.


If you go to Wikipedia right now, they say it’s
They’re using a Fibonacci heap instead of a binary heap.
is the right running time for this class.

Shortest path summary:


- BFS works great (and fast -- time) if graph is unweighted.
- Dijkstra’s works for weighted graphs with no negative edges, but a bit slower
- Reductions!
CSE 373 SU 19 - ROBBIE WEBER 48

You might also like