Unit3
Unit3
CoSc 3094
Unit-3
Greedy Algorithms
D E F G D E F G
H H
Edges Weight
1 2 {1, 2} 1
1 2 3 {2, 3} 2
{4, 5} 3
4 6 4 5 6
{6, 7} 3
{1, 4} 4
4 3 5 8 6 {2, 5} 4
{4, 7} 4
7 {3, 5) 5
4 3
{2, 4} 6
{3, 6} 6
7
{5, 7} 7
{5, 6} 8
Hadi Hussen Unit 3– Greedy Algorithms 9
Step:2
Kruskal’s Algorithm for MST – Example 2
Select the minimum weight edge but no cycle.
Edges Weight
1 2 {1, 2} 1
1 2 3 {2, 3} 2
{4, 5} 3
4 6 4 5 6
{6, 7} 3
{1, 4} 4
4 3 5 8 6 {2, 5} 4
{4, 7} 4
7 {3, 5) 5
4 3
{2, 4} 6
{3, 6} 6
7
{5, 7} 7
{5, 6} 8
Hadi Hussen Unit 3– Greedy Algorithms 10
Step:3
Kruskal’s Algorithm for MST – Example 2
The minimum spanning tree for the given graph.
Edges Weight
1 2 {1, 2} 1
1 2 3 {2, 3} 2
{4, 5} 3
4
{6, 7} 3
{1, 4} 4
4 3 5 6 {4, 7} 4
4 3 Total Cost = 17
Write the kruskal’s Algorithm to find out Minimum Spanning Tree. Apply the same and find MST
for the graph given below.
𝟏. 𝟐.
10
3
3 A 1
F C
A 4 3 7
B 2 4
C 5
8 4
5 6
4 B D D E F G
4
H 3 2 8
2 1 9
3
G E
3 H
1 2
1 2 3 1
4 6 4 5 6
4 3 5 8 6
7
4 3
1 2
1 2 3 1 {1, 2}, {1, 4}
Node Edges
1 2
1 2 3 1
1, 2 {1, 2}
4
1, 2, 3 {2, 3}
1, 2, 3, 4 {1, 4}
4 3 5 6 1, 2, 3, 4, 5 {4, 5}
1, 2, 3, 4, 5, 7 {4, 7}
4 3 1, 2, 3, 4, 5, 6, 7 {6, 7}
Total Cost = 17
7
𝟏. 𝟐.
10
3
3 A 1
F C
A 4 3 7
B 2 4
C 5
8 4
5 6
4 B D D E F G
4
H 3 2 8
2 1 9
3
G E
3 H
5 30 2
100
Source node = 1
10 5 Step v C 2 3 4 5
20
Init. - {2, 3, 4, 5} 50 30 100 10
4 3
50 1 5 {2, 3, 4} 50 30 20 10
5 30 2
100
Source node = 1
10 5 Step v C 2 3 4 5
20
Init. - {2, 3, 4, 5} 50 30 100 10
4 3
50 1 5 {2, 3, 4} 50 30 20 10
2 4 {2, 3} 40 30 20 10
1–4–2
Compare cost of 1–4–3
Is there
Is there path
path from
from 11 -- 44 -- 532 Yes
No
(40) and
(70) and 1–3
1–2(50)
(30)
Hadi Hussen Unit 3 – Greedy Algorithms 25
Dijkstra’s Algorithm - Example
5 30 2
100
Source node = 1
10 5 Step v C 2 3 4 5
20
Init. - {2, 3, 4, 5} 50 30 100 10
4 3
50 1 5 {2, 3, 4} 50 30 20 10
2 4 {2, 3} 40 30 20 10
3 3 {2} 35 30 20 10
Compare cost of
Is there path from 1 - 3 - 542 Yes
No
1–3–2 and 1–2
Hadi Hussen Unit 3 – Greedy Algorithms 26
Exercises – Home Work
Write Dijkstra’s Algorithm for shortest path. Use the algorithm to find the shortest path from the
following graph.
1. 2.
2
2 A B
B D
10 4 1 3 10
1 4 8 7 9 2 2
A C D E
3 2 5 8 4 6
C E
1
F G