Professional Documents
Culture Documents
143
321
326
142
370
341
378
421
401
Topological Sort
Topological sorting problem: given digraph G = (V, E) ,
find a linear ordering of vertices such that:
for any edge (v, w) in E, v precedes w in the ordering
B
C
A
F
D
E
A
E
4
Topological Sort
Topological sorting problem: given digraph G = (V, E) ,
find a linear ordering of vertices such that:
for any edge (v, w) in E, v precedes w in the ordering
B
C
A
F
D
E
A
F
5
F
D
F
D
C
A
F
D
10
Select
F
11
12
Final Result:
A
13
E
F
Adjacency
list
14
15
16
A
D
0 A
1 B
1 C
2 D
2 E
In-Degree
array 0 F
Adjacency
list
17
dequeue
enqueue
Output A
B
A
D
R. Rao, CSE 326
0 A
0 B
1 C
1 D
2 E
In-Degree
array 0 F
Adjacency
list
18
2.
3.
A
D
19
20
Paths
Recall definition of a path in a tree same for graphs
A path is a list of vertices {v1, v2, , vn} such that
Chicago
Seattle
Example of a path:
Salt Lake City
San Francisco
Dallas
p = {Seattle, Salt
Lake City,
Chicago, Dallas,
San Francisco,
Seattle}
21
last):
p = {Seattle, Salt Lake City, San Francisco, Dallas}
p = {Seattle, Salt Lake City, Dallas, San Francisco, Seattle}
A cycle is a path that starts and ends at the same node:
22
Chicago
3.5
Seattle
2
2
2.5
2.5
length(p) = 5
cost(p) = 11.5
San Francisco
R. Rao, CSE 326
Dallas
23
24
25
H
G
C Source
D
E
H
26
H
G
C
D
On-board
example:
Find the shortest path from C to: A
E
B
H
27
28
A
1
3
E
3
29
additional hops
Shortest path from
C to A:
BFS: C A
(cost = 9)
Minimum Cost
Path = C E D A
(cost = 8)
A
1
3
9
8
E
3
30
E. W. Dijkstra
(1930-2002)
staff had to print out his e-mails and put them in his mailbox
31
32
33
Similar to BFS
Each vertex stores a cost for path from source
Vertex to be expanded is the one with least path cost
seen so far
$ Greedy choice always select current best vertex
$ Update costs of all neighbors of selected vertex
But unlike BFS, a vertex already visited may be updated
if a better path to it is found
34
2.
3.
B
1
1
While there are unknown nodes left in the
9
graph
3
1. Select the unknown node N with the
C
8
2
lowest cost (greedy choice)
D
3
2. Mark N as known
E
3. For each node X adjacent to N
If (Ns cost + cost of (N, X)) < Xs cost
(Prev allows
Xs cost = Ns cost + cost of (N, X)
paths to be
Prev[X] = N //store preceding node
reconstructed)
35
known
cost
No
Prev
No
Yes
No
No
vertex known
Initial
D
R. Rao, CSE 326
Prev
Final
cost
E
36
known
cost
Prev
vertex
known
cost
Prev
No
Yes
No
Yes
10
Yes
Yes
No
Yes
No
Yes
Initial
Final
D
R. Rao, CSE 326
E
37
38