cs3329 Assignment
cs3329 Assignment
ID:1596879
1. [ 5+5] Use Kruskal's algorithm to find a minimal spanning tree for the weighted graph shown below,
showing steps. Then, use Prim's algorithm to do the same thing, using the same weighted graph, again
showing steps.
Kruskal algorithm
To start, we’ll be picking the smallest edge. In this case would be AB with the smallest edge weight of 2.
We repeatly look for the smallest edges that don’t create cycle. In this case edge CD with the edge weight
of 3 was chosen. The next are EF(4), CG(5), EG(7), and finally AF(8).
Prim’s algorithm
First we will create a empty list X = {}; This list will be use to keep track on nodes we have touched
First we will chose a nodes. We will chose node A. The list is now X ={A}
We’ll then examine all vertices reachable from A then choose the smallest edges that connect to an
unvisited node ( AB ). X = {A;B}
We’ll now look at all nodes that is reachable from A and B and continue picking the smallest edges that
connect to an unvisited nodes. In this case we will pick AF with only the edge weight of 8. X = {A;B;F}
Continue the process. We will pick unvisited node FE with the smallest edge weight of 4. X={A;B;F;E}
2. Use Bellman-Ford algorithm to find single source shortest path for the weighted graph shown
below, showing all the steps
1st iteration
Nodes 1 2 3 4 5
Value 0 6 4 7 2
2nd iteration
Nodes 1 2 3 4 5
Value 0 2 4 7 2
3rd iteration
Nodes 1 2 3 4 5
Value 0 2 4 7 -2
4th iteration
Nodes 1 2 3 4 5
Value 0 2 4 7 -2
Shortest path
3. Use Dijkstra algorithm to find shortest path between source and destination for the weighted
graph shown below, showing all the steps
We will chose the shortest path from one node to every other.
First set A = 0;
We can now reach C with the cost of 1 and D with the cost of 2 so we’ll pick C.
C = 1 => B = 1 +2 = 3 => F= B + 3 = 6;
D = 1 + 1 = 2;
E = 1 + 3 = 4; => F = E + 2 = 6;
We will pick D with the lowest edge weight.
D = 2; => G = 2 + 1 = 3
We will pick G with the lowest edge weight.
G = 3 => F = 3 + 1 = 4;
We will pick F with the lowest edge weight
4. Starting from node A, find DFS and BFS for the graph shown below. Show all your steps.
Breadth-first search
- Enqueue: A
- Enqueue: B-> C -> D
- Dequeue: A
- Enqueue : E -> F
- Dequeue: B -> C -> D
- Dequeue: E -> F
Breadth-first search will follow this search order : A -> B -> C -> D -> E -> F.
Depth-first search
Depth-first search will follow this search order A -> B -> E -> F -> C -> D
5. [10] Consider a modification of the rod-cutting problem in which, in addition to a price pi for each
rod, each cut incurs a fixed cost c. The revenue associated with a solution is now the sum of the prices of
the pieces minus the cost of making the cuts. Give a dynamic programming algorithm in pseudo code
format to solve this modified problem
if max > q
q = max
r[n] = q
return q