0% found this document useful (0 votes)
53 views

UNIT 2 - CS3401-Algorithms

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
53 views

UNIT 2 - CS3401-Algorithms

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 22

Graph Traversal Example: DFS

Graph traversal means visiting every vertex and edge exactly once in
a well-defined order in the graph. The traversing will start from the Source Node 1. Push Node 1
There are two types of Graph traversal. to the top of the stack. Node 1 will be marked as 'visited'.
1. Depth First Search (DFS)
2. Breadth First Search (BFS)
DFS is implemented using Stack (LIFO: Last-In-First-Out). BFS is
implemented using Queue (FIFO: First-In-First-Out).

1) Depth First Search (DFS)


DFS traverses according to graph depth. The algorithm starts at the
root node and explores as far as possible (depthwise) along each
Visit the unvisited neighbours and push Node 2 to the top of
branch before backtracking. DFS traverse the graph depthwise.
the stack. Node 2 will be marked as 'visited'.

DFS(G, s) //Where G is graph and s is source vertex


let S be stack
Visit the unvisited neighbours and push Node 4 to the top of
S.push( s )
mark s as visited. the stack. Node 4 will be marked as 'visited'.
while ( S is not empty):
//Pop a vertex from stack to visit next
v = S.top( )
S.pop( )

//Push all the neighbours of v in stack that are not visited


for all neighbours w of v in Graph G:
if w is not visited :
S.push( w )
mark w as visited

CS3401-ALGORITHMS (Sem-IV-R2021) - UNIT-II: 1


Visit the unvisited neighbours and push Node 5 to the top of Pop Node 4 from the stack.
the stack. Node 5 will be marked as 'visited'.

Pop Node 2 from the stack.

Visit the unvisited neighbours and push Node 3 to the top of


the stack. Node 3 will be marked as 'visited'. Pop Node 1 from the stack.

The stack is empty and it comes out of the loop. All the nodes
have been traversed by using DFS.

Complexity of Depth-First Search algorithm


All nodes are already marked as ‘Visited’.
Pop Node 3 from the stack. The time complexity of the DFS algorithm is O(V+E), where V
is the number of vertices and E is the number of edges in the
graph.

The space complexity of the DFS algorithm is O(V), where V is


the number of vertices.
Pop Node 5 from the stack.

CS3401-ALGORITHMS (Sem-IV-R2021) - UNIT-II: 2


2) Breadth First Search (BFS) Example: BFS
BFS traverses according to graph level (breadthwise). The
algorithm starts traversing from source node and traverse the The traversing will start from the source Node S and enqueue
Node S. Node S will be marked as 'visited'.
graph layerwise (level-by-level).

BFS traverse the graph breadthwise:


 First move horizontally and visit all the nodes of the
current layer
 Move to the next layer

Dequeue Node S and visit the unvisited neighbours and


enqueue them. Node 1 and Node 2 will be marked as 'visited'.

BFS (G, s): //Where G is the graph and s is the source node
let Q be queue.
Q.enqueue( s ) //Inserting s in queue
mark s as visited.
while ( Q is not empty)
v = Q.dequeue( ) //Removing that vertex from queue Dequeue Node 1 and visit the unvisited neighbours and
enqueue them. Node 3 will be marked as 'visited'.
//processing all the neighbours of v
for all neighbours w of v in Graph G
if w is not visited
Q.enqueue( w ) //Stores w in Q
mark w as visited.

CS3401-ALGORITHMS (Sem-IV-R2021) - UNIT-II: 3


Dequeue Node 2 and visit the unvisited neighbours and Complexity of Breadth-First Search algorithm
enqueue them. Node 4 will be marked as 'visited'.
The time complexity of the BFS algorithm is O(V+E), where V
is the number of vertices and E is the number of edges in the
graph.

The space complexity of the BFS algorithm is O(V), where V is


the number of vertices.

Dequeue Node 3 and visit the unvisited neighbours and


enqueue them. Node 5 will be marked as 'visited'.

All nodes are already marked as ‘Visited’.


Dequeue Node 4.

Dequeue Node 5.

The queue is empty and it comes out of the loop. All the nodes
have been traversed by using BFS.
CS3401-ALGORITHMS (Sem-IV-R2021) - UNIT-II: 4
Shortest Path Algorithm Choose a starting vertex and assign infinity path values to all
The shortest path algorithms calculate the minimum other vertices.
travelling cost from source node to destination node of a graph
in optimal time and space complexities.
The shortest path problem is about finding a path between
vertices in a graph such that the total sum of the edges weights
is minimum.

Types of shortest path algorithms: single-source and all-pairs.


Bellman-Ford Algorithm Single-Source vertex to all other vertices
Dijkstra’s Algorithm Single-Source vertex to all other vertices
Floyd-Warshall Algorithm Between All pairs of vertices Visit each edge and relax the path distances. This procedure
must be repeated V-1 times, where V is the number of vertices
1) Bellman-Ford Algorithm in total.
Bellman ford algorithm is a Single-Source Shortest Path
Algorithm. This algorithm is used to find the shortest distance
from the single vertex to all the other vertices of a graph.

The distance is initially unknown and assumed to be infinite,


later the algorithm relaxes paths by identifying a few shorter
paths. Bellman-Ford is based on “Principle of Relaxation”.

Example:

CS3401-ALGORITHMS (Sem-IV-R2021) - UNIT-II: 5


Complexity Analysis of Bellman-Ford Algorithm

Time Complexity
Best Case Average Case Worst Case
O(E) O(VE) O(VE)

Space Complexity
The space complexity is O(V).

BellmanFord(G, S)
for each vertex V in G
distance[V] <- infinite
previous[V] <- NULL
distance[S] <- 0

for each vertex V in G


for each edge (U,V) in G
Since the graph has five vertices so it will have four iterations.
tempDistance <- distance[U] + edge_weight(U, V)
if tempDistance < distance[V]
The final distances from the source vertex A to all other vertices
distance[V] <- tempDistance
are as follows: previous[V] <- U

Distance to B: 3 (A->C->B) for each edge (U,V) in G


Distance to C: 2 (A->C) If distance[U] + edge_weight(U, V) < distance[V}
Distance to D: 1 (A->C->B->E->D) Error: Negative Cycle Exists
Distance to E: 6 (A->C->B->E)
return distance[], previous[]

CS3401-ALGORITHMS (Sem-IV-R2021) - UNIT-II: 6


2) Dijkstra’s Algorithm Vertex ‘a’ is chosen.
Dijkstra’s Algorithm is a Single-Source Shortest Path Algorithm. The outgoing edges of vertex ‘a’ are relaxed.
It computes the shortest path from one particular source node Unvisited set : {b , c , d , e}
Visited set : {S , a}
to all other remaining nodes of the graph.

Example: Using Dijkstra’s Algorithm, find the shortest distance


from source vertex ‘S’ to remaining vertices in the following graph
Also, write the order in which the vertices are visited.

Unvisited set : {S , a , b , c , d , e}
Visited set :{}

Vertex ‘d’ is chosen.


The outgoing edges of vertex ‘d’ are relaxed.
Unvisited set : {b , c , e}
Visited set : {S , a , d}

Vertex ‘S’ is chosen.


The outgoing edges of vertex ‘S’ are relaxed.
Unvisited set : {a , b , c , d , e}
Visited set : {S}
Vertex ‘b’ is chosen.
The outgoing edges of vertex ‘b’ are relaxed. (d=5 > 2)
No change
Unvisited set : {c , e}
Visited set : {S , a , d , b}

CS3401-ALGORITHMS (Sem-IV-R2021) - UNIT-II: 7


Vertex ‘c’ is chosen. The final distances from the source vertex S to all other vertices are
The outgoing edges of vertex ‘c’ are relaxed. (e=4) as follows:
No change Distance to a: 1 (S->a)
Unvisited set : {e} Distance to b: 3 (S->a->b)
Visited set : {S , a , d , b , c} Distance to c: 3 (S->a->c)
Distance to d: 2 (S->a->d)
Distance to e: 4 (S->a->d->e)

Complexity Analysis of Dijkstra's Algorithm

Time Complexity
Vertex ‘e’ is chosen. Best Case Average Case Worst Case
There are no outgoing edges for vertex ‘e’. O((V + E) log V) O((V + E) log V) O((V2) log V)
Unvisited set : { }
Visited set : {S , a , d , b , c , e}
Space Complexity
All vertices of the graph are processed. The space complexity is O(V)

dijkstra(G, S)
for each vertex V in G
distance[V] <- infinite
previous[V] <- NULL
If V != S, add V to Priority Queue Q
distance[S] <- 0

while Q IS NOT EMPTY


U <- Extract MIN from Q
for each unvisited neighbour V of U
tempDistance <- distance[U] + edge_weight(U, V)
It represents the shortest path from source vertex ‘S’ to all other if tempDistance < distance[V]
vertices. distance[V] <- tempDistance
previous[V] <- U
The order in which all the vertices are processed is: return distance[], previous[]
S, a, d, b, c, e.

CS3401-ALGORITHMS (Sem-IV-R2021) - UNIT-II: 8


3) Floyd-Warshall Algorithm
Floyd-Warshall Algorithm is an algorithm for finding the
shortest path between all the pairs of vertices in a graph.

It works by keeping a matrix of distances between each pair of


vertices and updating this matrix iteratively till the shortest
paths are discovered.

CS3401-ALGORITHMS (Sem-IV-R2021) - UNIT-II: 9


The resultant matrix gives the shortest path between each pair
of vertices.

Complexity Analysis of Floyd-Warshall Algorithm

Time Complexity: O(V3), where V is the number of vertices in


the graph and run three nested loops each of size V

Auxiliary Space: O(V2), to create a 2-D matrix in order to store


the shortest distance for each pair of nodes.

CS3401-ALGORITHMS (Sem-IV-R2021) - UNIT-II: 10


Example 2 Calculate the distance from the source vertex to destination
vertex through this vertex 2

Calculate the distance from the source vertex to destination


vertex through this vertex 3
Initialize the Distance[][] matrix using the input graph

Calculate the distance from the source vertex to destination


vertex through this vertex 4
Calculate the distance from the source vertex to destination
vertex through this vertex 1

The resultant matrix gives the shortest path between each pair
of vertices.

CS3401-ALGORITHMS (Sem-IV-R2021) - UNIT-II: 11


Minimum Spanning Tree (MST) Example:
Minimum Spanning Tree (MST) is the spanning tree
where the cost is minimum among all the spanning trees. The
cost of the spanning tree is the sum of the weights of all the
edges in the tree.

Algorithms for finding the Minimum Spanning Tree


 Kruskal’s Algorithm
 Prim’s Algorithm
Sort all the edges of the given graph in an ascending order and store
the values in an array.
1) Kruskal’s Algorithm
a. Sort all the edges from low weight to high
b. Take the edge with the lowest weight and add it to the
spanning tree. If adding the edge created a cycle, then reject
this edge.
c. Keep adding edges until we reach all vertices.

MST_Kruskal(Edges, V, E):
e=0, i=0
sum=0
Sort(Edges) From the list of sorted edge costs, select the least cost edge
while(e<V-1): B→D=5
u=Edges[i].u Minimum cost = 5
v=Edges[i].v Visited array, v = {B, D}
if(Adding edge {u, v} do not form cycle):
Print(Adding edge {u, v} to MST)
sum=sum + Edges[i].weight
e=e+1
i=i+1

CS3401-ALGORITHMS (Sem-IV-R2021) - UNIT-II: 12


The next least cost edge is A → B = 6 The next least cost edge is B → C = 11
Minimum cost = 5 + 6 = 11 Minimum cost = 5 + 6 + 9 + 10 + 11 = 41
Visited array, v = {B, D, A} Visited array, v = {B, D, A, C, F, E}

The next least cost edge is C → F = 9 The next least cost edge is G → F = 12
Minimum Cost = 5 + 6 + 9 = 20 Minimum cost = 5 + 6 + 9 + 10 + 11 + 12 = 53
Visited array, v = {B, D, A, C, F} Visited array, v = {B, D, A, C, F, E, G}

The obtained result is the minimum spanning tree of the given graph
The next least cost edge is F → E = 10
with cost = 53
Minimum Cost = 5 + 6 + 9 + 10 = 30
Visited array, v = {B, D, A, C, F, E}
Complexity Analysis of Kruskal’s Algorithm

The time complexity of Kruskal’s algorithm is O(E logE) or O(V logV),


where V is the number of vertices and E is the number of edges in
the graph.

The space complexity of Kruskal’s algorithm is O(V + E), where V is


the number of vertices and E is the number of edges in the graph.

CS3401-ALGORITHMS (Sem-IV-R2021) - UNIT-II: 13


2) Prim’s Algorithm Example: Find the minimum spanning tree using prim’s method
a. Initialize the minimum spanning tree with a vertex (greedy approach) for the graph given below with S as the arbitrary
chosen at random. root.
b. Find all the edges that connect the tree to new vertices,
find the minimum and add it to the tree
c. Keep repeating step 2 until we get a minimum spanning
tree.

MST_Prim(G):
T = ∅;
U = { 1 }; Create a visited array to store all the visited vertices
while (U ≠ V) V={}
let (u, v) be the lowest cost edge such that u ∈ U and v ∈ V - U; The arbitrary root is S.
Find the least cost edge that are connected to S.
T = T ∪ {(u, v)}
S→B=8
U = U ∪ {v}
Minimum cost = 8
 Prim's algorithm shows how we create two sets of vertices
V = {S, B}
U and V-U.
 U contains the list of vertices that have been visited and
V-U the list of vertices that haven't.
 One by one, we move vertices from set V-U to set U by
connecting the least weight edge.
Since B is the last visited, check for the least cost edge that is
connected to the vertex B.
B→A=9
Minimum cost = 8 + 9 = 17
V = {S, B, A}

CS3401-ALGORITHMS (Sem-IV-R2021) - UNIT-II: 14


Since A is the last visited, check for the least cost edge that is Since D is the last visited, check for the least cost edge that is
connected to the vertex A. connected to the vertex D.
A → E = 11 D → C = 15
Minimum cost = 8 + 9 + 11 = 28 Minimum cost = 8 + 9 + 11 + 3 + 15 = 46
V = {S, B, A, E} V = {S, B, A, E, D, C}

Since E is the last visited, check for the least cost edge that is
connected to the vertex E.
The minimum spanning tree is obtained with the minimum cost = 46
E→D=3
Minimum cost = 8 + 9 + 11 + 3 = 31
Complexity Analysis of Prim’s Algorithm
V = {S, B, A, E, D}

The time complexity of prim's algorithm is O((V + E) log V), where V


is the number of vertices and E is the number of edges in the graph.

The space complexity of prim's algorithm is O(V + E), where V is the


number of vertices and E is the number of edges in the graph.

CS3401-ALGORITHMS (Sem-IV-R2021) - UNIT-II: 15


1) Define Graph. What are the different types of Graph? 3) What are the ways to represent a graph?
Graph is composed of a set of vertices(V) and a set of edges (E).
The graph is denoted by G(V, E). Representation of Graphs

 Adjacency Matrix
Graph is represented in the form of the 2D matrix where rows
and columns denote vertices. Each entry in the matrix
represents the weight of the edge between those vertices.

Two types of Graph


 Undirected graph − Undirected graphs have edges that
do not have a direction. The edges indicate a two-way
relationship, in that each edge can be traversed in both
directions.
 Directed graph − Directed graphs have edges with
direction. The edges indicate a one-way relationship, in
that each edge can only be traversed in a single
direction.  Adjacency List
Graph is represented as a collection of linked lists. There is an
array of pointer which points to the edges connected to that
vertex.

2) What are graph algorithms?


Graph algorithms are methods used to manipulate and analyze
graphs. Graph algorithms are a set of instructions that
traverse graph.
 Breadth First Search (BFS)
 Depth First Search (DFS)
 Bellman-Ford Algorithm
 Dijkstra’s Algorithm
 Floyd-Warshall Algorithm

CS3401-ALGORITHMS (Sem-IV-R2021) - UNIT-II: 16


4) What is bi-connectivity? (bi-connected Graph) 6) What is connectivity? (connected graph)
Graph G=(V,E) is a bi-connected graph if it is connected and A graph is said to be connected graph if there is a path between
there are no articulation points (no cut vertex). every pair of vertex. From every vertex to any other vertex there
must be some path to traverse. This is called the connectivity
of a graph.

A graph is said to be bi-connected if: It is possible to travel from one vertex to another vertex. Here,
 It is connected. (It is possible to reach every vertex from we can traverse from vertex B to H using the path B -> A -> D
every other vertex by a simple path) -> F -> E -> H. Hence it is a connected graph.
 There are two disjoint paths between any two vertices.
 There exists simple cycle between two vertices.
 There should not be any cut vertex (Cut vertex is a 7) What is flow networks?
vertex which if we remove then the graph becomes A flow network is a directed graph G = (V,E) with vertices S
disconnected.) (source) and T (sink), in which each edge (u,v) ∈ E has a non-
negative capacity c(u,v).
5) What is strong connectivity? (strong connected graph)
A directed graph is strongly connected if there is directed path
from any vertex to every other vertex.

Directed graph is called strongly connected if there exists a


path in each possible direction between each pair of vertices in
the graph.

Flow network is used to describe a network of vertices and


edges with a source (S) and a sink (T). S can only send and T
can only receive.

Strongly connected components are represented by dotted


marking.

CS3401-ALGORITHMS (Sem-IV-R2021) - UNIT-II: 17


8) Explain Ford-Fulkerson method. 10) What is maximum Bipartite matching? (maximum
Ford-Fulkerson algorithm is a greedy approach for calculating cardinality matching)
the maximum possible flow in a network or a graph to reach Bipartite Matching is Matching in a bipartite graph where
from start to destination. each edge has unique vertex. (no two edges share the same
vertex)
Ford-Fulkerson can find a maximum matching in a bipartite
graph in O(mn) time. Maximum Bipartite Matching is the problem of computing a
matching of maximum cardinality (maximum number of
edges) in a bipartite graph.

9) What is Bipartite Graph?


A Bipartite Graph is a graph whose vertices can be divided into
two independent sets, U and V such that every edge (u, v) either
connects a vertex from U to V or a vertex from V to U.

A bipartite graph is a graph whose vertex set is partitioned into 11) What is graph traversal?
two disjoint sets L, R such that each edge has one endpoint in Graph traversal means visiting every vertex and edge exactly
L and the other endpoint in R. once in a well-defined order in the graph.
There are two types of Graph traversal.
1. Depth First Search (DFS)
2. Breadth First Search (BFS)
DFS is implemented using Stack (LIFO: Last-In-First-Out).
BFS is implemented using Queue (FIFO: First-In-First-Out).

In the above image, nodes of the same colour belong to the


same set.

CS3401-ALGORITHMS (Sem-IV-R2021) - UNIT-II: 18


12) Outline DFS with an example. 14) Write down the steps to perform DFS.
DFS traverses according to graph depth. The algorithm starts
at the root node and explores as far as possible (depthwise)
DFS(G, s) //Where G is graph and s is source vertex
along each branch before backtracking. DFS traverse the let S be stack
graph depthwise. S.push( s )
mark s as visited.
while ( S is not empty):
//Pop a vertex from stack to visit next
v = S.top( )
S.pop( )

//Push all the neighbours of v in stack that are not visited


for all neighbours w of v in Graph G:
if w is not visited :
S.push( w )
mark w as visited
13) Outline BFS with an example.
BFS traverses according to graph level (breadthwise).
The algorithm starts traversing from source node and 15) Write down the steps to perform BFS.
traverse the graph layerwise (level-by-level).
BFS (G, s): //Where G is the graph and s is the source node
BFS traverse the graph breadthwise: let Q be queue.
 First move horizontally and visit all the nodes of Q.enqueue( s ) //Inserting s in queue
mark s as visited.
the current layer while ( Q is not empty)
 Move to the next layer v = Q.dequeue( )//Removing that vertex from queue

//processing all the neighbours of v


for all neighbours w of v in Graph G
if w is not visited
Q.enqueue( w ) //Stores w in Q
mark w as visited.

CS3401-ALGORITHMS (Sem-IV-R2021) - UNIT-II: 19


16) Discuss the time and space complexity of DFS and BFS. 18) Outline the Bellman ford algorithm.
Bellman ford algorithm is a Single-Source Shortest Path
Complexity of Depth-First Search algorithm Algorithm. This algorithm is used to find the shortest
The time complexity of the DFS algorithm is O(V+E), where V
distance from the single vertex to all the other vertices
is the number of vertices and E is the number of edges in the
graph. of a graph.
The space complexity of the DFS algorithm is O(V), where V
is the number of vertices. The distance is initially unknown and assumed to be
infinite, later the algorithm relaxes paths by identifying
Complexity of Breadth-First Search algorithm
a few shorter paths. Bellman-Ford is based on “Principle
The time complexity of the BFS algorithm is O(V+E), where V
of Relaxation”.
is the number of vertices and E is the number of edges in the
graph.
BellmanFord(G, S)
The space complexity of the BFS algorithm is O(V), where V
for each vertex V in G
is the number of vertices.
distance[V] <- infinite
17) What is shortest path algorithm and list its types. previous[V] <- NULL
The shortest path algorithms calculate the minimum distance[S] <- 0
travelling cost from source node to destination node of a
for each vertex V in G
graph in optimal time and space complexities.
for each edge (U,V) in G
tempDistance <- distance[U] + edge_weight(U, V)
The shortest path problem is about finding a path
if tempDistance < distance[V]
between vertices in a graph such that the total sum of distance[V] <- tempDistance
the edges weights is minimum. previous[V] <- U

Types of shortest path algorithms: single-source and all- for each edge (U,V) in G
pairs. If distance[U] + edge_weight(U, V) < distance[V}
Error: Negative Cycle Exists
Bellman-Ford Algorithm Single-Source vertex to all other
vertices return distance[], previous[]
Dijkstra’s Algorithm Single-Source vertex to all other
vertices
Floyd-Warshall Algorithm Between All pairs of vertices

CS3401-ALGORITHMS (Sem-IV-R2021) - UNIT-II: 20


19) Outline the Dijkstra’s Algorithm. 21) Discuss the time and space complexity of various
Dijkstra’s Algorithm is a Single-Source Shortest Path shortest path algorithm.
Algorithm. It computes the shortest path from one particular
source node to all other remaining nodes of the graph. Complexity Analysis of Bellman-Ford Algorithm

dijkstra(G, S) Time Complexity


for each vertex V in G Best Case Average Case Worst Case
distance[V] <- infinite
previous[V] <- NULL
O(E) O(VE) O(VE)
If V != S, add V to Priority Queue Q
distance[S] <- 0 Space Complexity
The space complexity is O(V).
while Q IS NOT EMPTY
U <- Extract MIN from Q
for each unvisited neighbour V of U Complexity Analysis of Dijkstra's Algorithm
tempDistance <- distance[U] + edge_weight(U, V)
if tempDistance < distance[V] Time Complexity
distance[V] <- tempDistance
Best Case Average Case Worst Case
previous[V] <- U
return distance[], previous[] O((V + E) log V) O((V + E) log V) O((V2) log V)

20) Outline the Floyd-Warshall Algorithm. Space Complexity


Floyd-Warshall Algorithm is an algorithm for finding the
The space complexity is O(V)
shortest path between all the pairs of vertices in a graph.

Complexity Analysis of Floyd-Warshall Algorithm


It works by keeping a matrix of distances between each pair
of vertices and updating this matrix iteratively till the shortest
paths are discovered. Time Complexity: O(V3), where V is the number of
vertices in the graph and run three nested loops each of
size V

Space Complexity: O(V2), to create a 2-D matrix in order


to store the shortest distance for each pair of nodes.

CS3401-ALGORITHMS (Sem-IV-R2021) - UNIT-II: 21


22) What is minimum spanning tree? 24) Outline Prim’s Algorithm.
Minimum Spanning Tree (MST) is the spanning tree a. Initialize the minimum spanning tree with a vertex
where the cost is minimum among all the spanning trees. The chosen at random.
cost of the spanning tree is the sum of the weights of all the b. Find all the edges that connect the tree to new vertices,
edges in the tree. find the minimum and add it to the tree
c. Keep repeating step 2 until we get a minimum
Algorithms for finding the Minimum Spanning Tree spanning tree.
 Kruskal’s Algorithm MST_Prim(G):
 Prim’s Algorithm T = ∅;
U = { 1 };
23) Outline Kruskal’s Algorithm. while (U ≠ V)
Kruskal’s Algorithm let (u, v) be the lowest cost edge such that u ∈ U and v ∈ V - U;
a) Sort all the edges from low weight to high T = T ∪ {(u, v)}
b) Take the edge with the lowest weight and add it to the U = U ∪ {v}
spanning tree. If adding the edge created a cycle, then
reject this edge. 25) Discuss the time and space complexity of various
c) Keep adding edges until we reach all vertices. minimum spanning tree algorithm.
Complexity Analysis of Kruskal’s Algorithm
MST_Kruskal(Edges, V, E): The time complexity of Kruskal’s algorithm is O(E logE) or
e=0, i=0 O(V logV), where V is the number of vertices and E is the
sum=0 number of edges in the graph.
Sort(Edges) The space complexity of Kruskal’s algorithm is O(V + E),
where V is the number of vertices and E is the number of
while(e<V-1):
edges in the graph.
u=Edges[i].u
v=Edges[i].v Complexity Analysis of Prim’s Algorithm
if(Adding edge {u, v} do not form cycle): The time complexity of prim's algorithm is O((V + E) log V),
Print(Adding edge {u, v} to MST) where V is the number of vertices and E is the number of
sum=sum + Edges[i].weight edges in the graph.
e=e+1 The space complexity of prim's algorithm is O(V + E), where
i=i+1 V is the number of vertices and E is the number of edges in
the graph.

CS3401-ALGORITHMS (Sem-IV-R2021) - UNIT-II: 22

You might also like