Lecture 09
Lecture 09
¢ Graph
¢ Adjacency Matrix
¢ Adjacency List
¢ Greedy algorithms
¢ Shortest Distance
¢ Dijkstra’s Algorithm
¢ Kruskal’s Algorithm
¢ Prim’s Algorithm
3
¢ A graph is a set of nodes (vertices) joined by
edges (arcs).
¢ A graph may be directed or undirected
12
13
14
17
5 2
30
100
10
5
20
4 3
50
18
1
10 50
5 2
30
100
10
5
20
4 3 19
50
1
10 50
5 2
30
100
10
5
20
4 3 20
50
1
10 50
5 2
30
D=10 100
10
5
20
End of Step 0
4 3 21
50
1
10 50
5 2
30
D=10 100
10
5
20
4 3 22
50
1
10 50
5 2
30
D=10 100
10
5
20
End of Step 1
4 3 23
50
D=20
CSC1203 - Data Structures & Algorithms
¢ Dijkstra’s Algorithm: An Example
1
10 50
5 2
30
D=10 100
10
5
20
4 3 24
50
D=20
CSC1203 - Data Structures & Algorithms
¢ Dijkstra’s Algorithm: An Example
1
10 50
5 2
30
D=10 100
10
5
20
End of Step 2
4 3 25
50 D=30
D=20
CSC1203 - Data Structures & Algorithms
¢ Dijkstra’s Algorithm: An Example
1
10 50
5 2
30
D=10 100
10
5
20
4 3 26
50 D=30
D=20
CSC1203 - Data Structures & Algorithms
¢ Dijkstra’s Algorithm: An Example
1
10 50
5 2
30
D=10 100
10
5
20
4 3 27
50 D=30
D=20
CSC1203 - Data Structures & Algorithms
¢ Dijkstra’s Algorithm: An Example
1
10 50
5 2
30
D=10 100
10
5
20
4 3 28
50 D=30
D=20
CSC1203 - Data Structures & Algorithms
¢ Dijkstra’s Algorithm: An Example
1
10 50
5 2
30
D=10 100 D=35
10
5
20
End of Step 2
4 3 29
50 D=30
D=20
CSC1203 - Data Structures & Algorithms
Dijkstra’s Algorithm
¢ Uses two sets of nodes S and C
¢ At each iteration S contains the set of
nodes that have already been chosen
¢ At each iteration C contains the set of
nodes that have not yet been chosen
¢ At each step we move the node which is
cheapest to reach from C to S
¢ An arrayD contains the shortest path so
far from the source to each node
30
31
34
1 1 2 2 3 1 1 2 2 3
6 5
4 4 6 4
3
3 8
4 5 6 4 5 6
7
4 3 4 3
G 7 G¢ 7
35
36
38
1 1 2 2 3 1 2 3
6
4 4 5 6
3
4 5 8 6 4 5 6
7
4
3
G 7 G¢ 7
39
1 2 2 3 1 1 2 3
6 5
4 4 6
3 8
4 5 6 4 5 6
4 7 3
G 7 G¢ 7
40
1 2 2 3 1 1 2 3
6 5
4 4 6
3 8
4 5 6 4 5 6
4 7
3
G 7 G¢ 7
41
1 2 2 3 1 1 2 3
6 5
4 4 6
3 8
4 5 6 4 5 6
4 7 3
G 7 G¢ 7
42
1 2 2 3 1 1 2 3
6 5
4 4 6
3 8
4 5 6 4 5 6
4 7 3
G 7 G¢ 7
43
1 2 2 3 1 1 2 3
6 5
4 4 6
3 8
4 5 6 4 5 6
4 7 3
G 7 G¢ 7
44
1 2 2 3 1 1 2 3
6 5
4 4 6
3 8
4 5 6 4 5 6
4 7 3
G 7 G¢ 7
45
1 2 2 3 1 1 2 3
6 5
4 4 6
3 8
4 5 6 4 5 6
4 7 3
G 7 G¢ 7
46
49
1 1 2 2 3 1
6
4 4 5 6
3
4 5 8 6
7
4
3
G 7 G¢
50
1 1 2 2 3 1 2
6
4 4 5 6
3
4 5 8 6
7
4
3
G 7 G¢
51
1 2 2 3 1 1 2 3
6 5
4 4 6
3 8
4 5 6
4 7 3
G 7 G¢
52
1 2 3 1 2 3
1 2
6 4 5 6 4
3 8
4 5 6 4
4 7 3
G 7 G¢
53
1 2 3 1 2 3
1 2
6 4 5 6 4
8 3
4 5 6 4 5
4 7 3
G 7 G¢
54
1 2 3 1 2 3
1 2
6 4 5 6 4
8 3
4 5 6 4 5
7 3 4
G 7 G¢ 7
55
1 2 3 1 2 3
1 2
6 4 5 6 4
8 3
4 5 6 4 5 6
7 4 3
G 7 G¢ 7
56