Lecture11 Graphs Part1
Lecture11 Graphs Part1
Lê Sỹ Vinh
Computational Science and Engineering
Email: [email protected]
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
2
7
1
HNL 255 3 1 38 9
10
9
5 LAX
1 23 7 11
DF 20
3 W MIA
3
Travel on graphs
BFS DFS
1 1
2 3 4 2 7 8
1
5 6 7 8 3 6 9
2
1 1 1 1 1
9 4 5
0 1 2 0 1
Shortest Paths
0
8 A 4
2
8 7 2 1 3
B C D
5 3 9 8
2 5
E F
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
1 84
SFO D 9 14
3
2
120
5
80
4 LGA
17
33
2
7
HNL 255 3 1 38 9
10
9
5 LAX
1 23 7 11
DF 20
3 W MIA
6
Shortest Paths
➢ Given a weighted graph and two vertices u and v, we want to find a
path of minimum total weight between u and v.
❖ Length of a path is the sum of the weights of its edges.
➢ Example:
❖ Shortest path between Providence and Honolulu
➢ Applications
❖ Internet packet routing
❖ Driving directions
OR 84 PVD
1 84
SFO D 9 14
3
2
120
5
4 80 LGA
7
33
2
7
1
HNL 255 3 1 38 9
10
9
5 LAX
1 23 7 11
DF 20
3 W
Phạm Bảo Sơn - DSA Dec 2008
MIA 7
Dijkstra Algorithm
Given G=(V, E), where weight (u,v) > 0 is the
weight of edge (u, v) ∈ E. Find the
shortest path from s to e.
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
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