Professional Documents
Culture Documents
Lecture 11 - Graphs - Part1
Lecture 11 - Graphs - Part1
1
Outlines
• Graph revisit
• Shortest paths
2
Graphs
• A graph is a pair (V, E), where
– V is a set of nodes, called vertices
– E is a collection of pairs of vertices, called edges
– Vertices and edges are positions and store elements
• Example:
– A vertex represents an airport and stores the three-letter airport code
– An edge represents a flight route between two airports and stores the mileage
of the route
OR 84 PVD
18 4
SFO D 9 14
3
2
7 4 80 LGA
33
1 2
7
BFS DFS
1 1
2 3 4 2 7 8
5 6 7 8 3 6 9 12
9 10 11 12 4 5 10 11
4
Shortest Paths
0
8 A 4
2
8 7 2 1 3
B C D
5 3 9 8
2 5
E F
5
Weighted Graphs
➢ In a weighted graph, each edge has an associated numerical value,
called the weight of the edge
➢ Edge weights may represent, distances, costs, etc.
➢ Example:
❖ In a flight route graph, the weight of an edge represents the distance in
miles between the endpoint airports
OR 84 PVD
184
SFO D 9 14
3
2
120
5
80
4 LGA
17
33
2
7
120
5
4 80 LGA
7
33
1 2
7
General idea
➢ Known = {the set of vertices which the d(u) =
shortest paths are known} 50 10 d(v) = 75
➢ Unknown = {the set of vertices which the u
s v
shortest paths are unknown}
The algorithm iteratively determine the
shortest paths of vertices in Unknown and
move them to Known.
∞ 3 9 ∞ 5 3 9 8
2 5 2 5
E F E F
0 0
8 A 4 8 A 4
2 2
8 7 2 1 3 7 7 2 1 3
B C D B C D
5 3 9 11 5 3 9 8
2 5 2 5
E F E F
10
Example (cont.)
0
8 A 4
2
7 7 2 1 3
B C D
5 3 9 8
2 5
E F
0
8 A 4
2
7 7 2 1 3
B C D
5 3 9 8
2 5
E F
11
Why It Doesn’t Work for Negative-
Weight Edges
0
8 A 4
6
7 7 5 1 4
B C D
5 0 -8 9
2 5
E F
12
Exercises
Write out the shortest path from A to H for the following graph
5
A B
2
2
3 6
C D
4
1 1
3 4 2
E F G H
13
Finding shortest paths for all
pairs of vertices
Complexity: O(n3)
14
Floyd algorithm Example
15
Exercise
Write out the matrix obtained from Floyd algorithm for the following
graph. 5
8
B F
2 1 2
4 3
A 7 D
4 3
5
2
C E
16