Professional Documents
Culture Documents
Weighted Graphs: CS221N, Data Structures
Weighted Graphs: CS221N, Data Structures
Weighted Graphs: CS221N, Data Structures
1
Weighted Graphs
Once again, a graph where edges have weights, which
quantifies the relationship
These graphs can be directed or undirected
2
Weighted Graph: Adjacency List
The adjacency list for a weighted graph contains edge
weights
Instead of 0 and 1
A B C D E F
A INF INF INF INF 0.1 0.9
B 0.3 INF 0.3 0.4 INF INF
C INF INF INF 0.6 0.4 INF
D INF INF INF INF 1 INF
E 0.55 INF INF INF INF 0.45
4
F INF INF INF 1 INF INF
Dijkstra’s Algorithm
Given a weighted graph, find the shortest path (in terms of edge
weights) between two vertices in the graph
Numerous applications
Cheapest airline fare between departure and arrival cities
Shortest driving distance in terms of mileage
5
Dijkstra’s Algorithm
Suppose in the graph below, we wanted the shortest path
from B to F
A C D E F
INF INF INF INF INF
7
Step 1
Take all edges leaving B,
and put their weights in
the table
Along with the source
vertex
A C D E F
0.3 (B) 0.3 (B) 0.4 (B) INF INF
8
Step 2
Pick the edge with the
smallest weight and
mark it as the shortest
path from B
(How do we know
that?)
And here is our table:
A C D E F
0.3* (B) 0.3 (B) 0.4 (B) INF INF
9
Step 3
Now choose one of the
edges with minimal weight
and repeat the process
(explore adj. vertices &
mark their total weight)
A C D E F
0.3* (B) 0.3 (B) 0.4 (B) INF INF
10
Step 4
In this case, we’ll look at A
Explore adjacent vertices
Enter the total weight
from B to those vertices
IF that weight is smaller than
the current entry in the table
Ignore the ones marked (*)
So here is our table:
A C D E F
0.3* (B) 0.3 (B) 0.4 (B) 0.4 (A) 1.2 (A)
11
Step 5
Now, A is marked and
we’ve visited its neighbors
So pick the lowest entry
in the table (in this case C)
and repeat the process
A C D E F
0.3* (B) 0.3* (B) 0.4 (B) 0.4 (A) 1.2 (A)
12
Step 6
Visit C’s neighbors that
are unmarked
Insert their total weight
into the table, IF it’s
smaller than the current
entry
A C D E F
0.3* (B) 0.3* (B) 0.4 (B) 0.4 (A) 1.2 (A)
13
Step 7
Now we visit D
Which only contains
one edge to E
A C D E F
0.3* (B) 0.3* (B) 0.4* (B) 0.4 (A) 1.2 (A)
14
Step 8
Now we visit E
Has two outgoing edges
One to A (marked, ignore)
One to F, which changes
the table to
0.4 + 0.45 = 0.85
Which is smaller than the
current entry, 1.2
A C D E F
0.3* (B) 0.3* (B) 0.4* (B) 0.4* (A) 0.85 (E)
15
Example
Let’s try this example with train costs:
17
Find the shortest path from D to all other
vertices!