Unit 2 Algorithm
Unit 2 Algorithm
GRAPH ALGORITHMS
Graph algorithms: Representations of graphs - Graph traversal: DFS – BFS –
applications - Connectivity, strong connectivity, bi-connectivity - Minimum
spanning tree: Kruskal’s and Prim’s algorithm- Shortest path: Bellman-Ford
algorithm - Dijkstra’s algorithm - Floyd-Warshall algorithm Network flow: Flow
networks - Ford-Fulkerson method – Matching: Maximum bipartite matching
PART A
1. Define a graph. (April/May 2007)
V3
2. Undirected Graphs.
A subgraph G’ of graph G is a graph such that the set of vertices and set
of edges of G’ are proper subset of the set of edges of G.
Example: V2
V1 V2
V3
V3
Example: V1 V2
V3 V4
Directed graph is a graph which consists of directed edges, where each edge
in E is unidirectional. It is also referred as Digraph. If (v,w) is a directed
edge then (v,w) ≠ (w,v)
V1 V2
V3
(v1,v2) ≠ (v2,v1)
V
(v1,v2) = (v2,v1)
8. Define cycle.
A cycle in a graph is a path in which first and last vertex are the same.
Path is 1 -> 2 -> 3 -> 1 1
2
A directed graph is said to be acyclic when there is no cycle path in it. It is also
called DAG (Directed Acyclic Graph).
Diagram: V1
V4
V2
V3
V5
A digraph is weakly connected if all the vertices are connected to each other.
• Depth-first traversal
• Breadth-first traversal
15. What is the degree of a graph?
Adjacency node is the node which is connected to the other nodes in the graph.
Example:
A C
B D
used. Solution: a b c d
19. What is a single source shortest path problem?
The single source shortest path problem finds the minimum cost from
single source vertex to all other vertices. Dijkstra’s algorithm is used to solve
this problem which follows the greedy technique.
20.Prove that the number of odd degree vertices in a connected graph
should be even. (May/June 2007)
Consider a graph with odd degree vertices.
Degree =1
This implies that the no. of vertices is even for odd degree graphs.
1 V1-V2-V3- 3
2 V1-V4-V5- 4
3 V1-V7-V8- 4
V1-V2-V3-V10 is the shortest path.
• Depth-first traversal
• Breadth-first traversal
Example:
1
2 3
Biconnected graphs are the graphs which cannot be broken into two
disconnected graphs by disconnecting single edge.
Example
In the given example, after removing edge E1 the graph does not become
disconnected.
26.What is a Spanning Tree?
Given an undirected and connected graph G=(V,E) a spanning tree of the
graph G is a tree that spans G (that is, it includes every vertex of G) and is a
subgraph of G (every edge in the tree belongs to G)
R(0),…,R(k-1),…,R(k),…,R(n)
Rules:
1. Start with computation of R(0). In R(0) any path with intermediate vertices is
not allowed. That means only direct edges towards the vertices are considered.
In other words the path length of one edge is allowed in R(0). Thus R(0) is
adjacency matrix for the digraph.
2. Construct R(1) in which first vertex is used as intermediate vertex and a path
length of two edge is allowed. Note that R(1) is build using R(0)which is already
computed.
3. Go on building R(k) by adding one intermediate vertex each time and with
more path length. Each R(k) has to be built from R(k-1)
4. The last matrix in this series is R(1), in this R(n) all the n vertices are used as
intermediate vertices. And the R(n) which is obtained is nothing but the
transitive closure of given digraph.
PART –B
Undirected Graph
Representation of Graphs
Graph data structure is represented using the following
representations.
1. Adjacency Matrix
2. Adjacency List
Adjacency Matrix
• In this representation, the graph can be represented
using a matrix of size n x n, where n is the number
of vertices.
• This matrix is filled with either 1’s or 0’s.
• Here, 1 represents that there is an edge from row
vertex to column vertex, and 0 represents that there is
no edge from row vertex to column vertex.
Directed graph representation
Adjacency list
• In this representation, every vertex of the graph
contains a list of its adjacent vertices.
• If the graph is not dense, i.e., the number of edges
is less, then it is efficient to represent the graph
through the adjacency list.
Adjacency List
• Graph traversal is a technique used to search for a
vertex in a graph. It is also used to decide the order
of vertices to be visited in the search process.
• A graph traversal finds the edges to be used in the
search process without creating loops. This means
that, with graph traversal, we can visit all the
vertices of the graph without getting into a looping
path. There are two graph traversal techniques:
1. DFS (Depth First Search)
2. BFS (Breadth-First Search)
Applications of graphs
1. Social network graphs : To tweet or not to tweet.
Graphs that represent who knows whom, who
communicates with whom, who influences whom, or other
relationships in social structures. An example is the
twitter graph of who follows whom.
2. Graphs in epidemiology: Vertices represent individuals
and directed edges to view the transfer of an infectious
disease from one individual to another. Analyzing such
graphs has become an important component in
understanding and controlling the spread of diseases.
2. Explain Floyd algorithm with example. Write down and explain the algorithm to
solve all pairs shortest paths problem. (APRIL/MAY 2010)(MAY/JUNE 2013).
Initial graph
Follow the steps below to find the shortest path between all the pairs of vertices.
1. Create a matrix A0 of dimension n*n where n is the number of vertices.
The row and the column are indexed as i and j respectively. i and j are the
vertices of the graph.
Each cell A[i][j] is filled with the distance from the ith vertex to the jth
vertex. If there is no path from ith vertex to jth vertex, the cell is left as
infinity.
Fill each cell with the distance between ith and jth vertex
2. Now, create a matrix A1 using matrix A0. The elements in the first column
and the first row are left as they are. The remaining cells are filled in the
following way.
Let k be the intermediate vertex in the shortest path from source to
destination. In this step, k is the first vertex. A[i][j] is filled with
(A[i][k] + A[k][j]) if (A[i][j] > A[i][k] + A[k][j]).
That is, if the direct distance from the source to the destination is greater than
the path h the vertex k, then the cell is filled with A[i][k] + A[k][j].
In this step, k is vertex 1. We calculate the distance from source vertex to destination
vertex.
Through this vertex
calculate the distance from the source vertex to destination vertex through this vertex k
For example: For A1[2, 4], the direct distance from vertex 2 to 4 is 4 and the
sum of the distance from vertex 2 to 4 through vertex (ie. from vertex 2 to 1 and
from vertex 1 to 4) is 7.
Since 4 < 7, A0[2, 4] is filled with 4.
3. Similarly, A2 is created using A1. The elements in the second column and the
second row are left as they are.
In this step, k is the second vertex (i.e. vertex 2). The remaining steps are the same as in step
Calculate the distance from the source vertex to destination vertex through this vertex 2
4. Similarly, A3 and A4 is also created.
Calculate the distance from the source vertex to
destination vertex through this vertex
Calculate the distance from the source vertex to destination vertex through this vertex 4
5. A4 gives the shortest path between each pair of vertices.
Floyd-Warshall Algorithm
n = no of vertices
A = matrix of
dimension n*n for k = 1
to n
for i = 1 to
n for j = 1
to n
Ak[i, j] = min (Ak-1[i, j], Ak-1[i, k]
+ Ak-1[k, j]) return A
Time Complexity
There are three loops. Each loop has constant complexities. So, the time
complexity of the Floyd- Warshall algorithm is O(n3).
3. How do you construct a minimum spanning tree? Explain?
Minimum Spanning Tree
A Spanning Tree is a tree which have V vertices and V-1 edges. All nodes in a
spanning tree are reachable from each other.
A Minimum Spanning Tree (MST) or minimum weight spanning tree for a
weighted, connected, undirected graph is a spanning tree having a weight less
than or equal to the weight of every other possible spanning tree. The weight of a
spanning tree is the sum of weights given to each edge of the spanning tree. In
short out of all spanning trees of a given graph, the spanning tree having minimum
weight is MST.
Algorithms for finding Minimum Spanning Tree (MST):-
1. Prim’s Algorithm
2. Kruskal’s Algorithm
4. Discuss about the algorithm and pseudocode to find the Minimum Spanning Tree
using Prim’s Algorithm.Discuss about the efficiency of the algorithm.
(MAY\JUNE 2016) (Apr 18)
Prim’s Algorithm
Prim's algorithm is a minimum spanning tree algorithm that takes a graph as
input and finds the subset of the edges of that graph which
• form a tree that includes every vertex
• has the minimum sum of weights among all the trees that can be formed from the
graph
How Prim's algorithm works
It falls under a class of algorithms called greedy algorithms that find the local
optimum in the hopes of finding a global optimum.
We start from one vertex and keep adding edges with the lowest weight until
we reach our goal. The steps for implementing Prim's algorithm are as follows:
1. Initialize the minimum spanning tree with a vertex chosen at random.
2. Find all the edges that connect the tree to new vertices, find the minimum
and add it to the tree
3. Keep repeating step 2 until we get a minimum spanning tree
Example of Prim's algorithm
Choose a vertex
Choose the nearest edge not yet in the solution, if there are multiple choices, choose one at
random
Prim's Algorithm pseudocode
The pseudocode for prim's algorithm shows how we create two sets of vertices 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.
T = ∅;
U = { 1 };
while (U ≠ V)
let (u, v) be the lowest cost edge such that u ∈ U and v ∈ V - U;
T = T ∪ {(u, v)}
U = U ∪ {v}
Prim's Algorithm Complexity
The time complexity of Prim's algorithm is O(E log V).
5. Apply Kruskal’s algorithm to find a minimum spanning tree of the following graph.
(NOV/DEC 2016)
Kruskal Algorithm
Kruskal's algorithm is a minimum spanning tree algorithm that takes a graph as
input and finds the subset of the edges of that graph which
• form a tree that includes every vertex
• has the minimum sum of weights among all the trees that can be formed from the
graph
How Kruskal's algorithm works
It falls under a class of algorithms called greedy algorithms that find the local
optimum in the hopes of finding a global optimum.
We start from the edges with the lowest weight and keep adding edges until we
reach our goal. The steps for implementing Kruskal's algorithm are as follows:
1. Sort all the edges from low weight to high
2. 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.
3. Keep adding edges until we reach all vertices.
Choose the edge with the least weight, if there are more than 1, choose anyone
Choose the next shortest edge that doesn't create a cycle and add it
Choose the next shortest edge that doesn't create a cycle and add it
6. Explain the Dijkstra’s shortest path algorithm and its efficiency. (NOV/DEC 2017)
Dijkstra Algorithm
Dijkstra's algorithm allows us to find the shortest path between any two vertices of a graph.
It differs from the minimum spanning tree because the shortest distance
between two vertices might not include all the vertices of the graph.
How Dijkstra's Algorithm works
Dijkstra's Algorithm works on the basis that any subpath B -> D of the shortest
path A -> D between vertices A and D is also the shortest path between vertices
B and D.
Each subpath is the shortest path
Djikstra used this property in the opposite direction i.e we overestimate the
distance of each vertex from the starting vertex. Then we visit each node and its
neighbors to find the shortest subpath to those neighbors.
The algorithm uses a greedy approach in the sense that we find the next best
solution hoping that the end result is the best solution for the whole problem.
Example of Dijkstra's algorithm
It is easier to start with an example and then think about the algorithm.
Choose a starting vertex and assign infinity path values to all other devices
Go to each vertex and update its path length
If the path length of the adjacent vertex is lesser than new path length, don't update it
After each iteration, we pick the unvisited vertex with the least path length. So we choose 5
before 7
Notice how the rightmost vertex has its path length updated twice
7. Write down the Dijkstra’s algorithm pseudocode its complexity and explain it with an example
(APR/MAY 11)
Djikstra's algorithm pseudocode
We need to maintain the path distance of every vertex. We can store that in an
array of size v, where v is the number of vertices.
We also want to be able to get the shortest path, not only know the length of the
shortest path. For this, we map each vertex to the vertex that last updated its path
length.
Once the algorithm is over, we can backtrack from the destination vertex to the
source vertex to find the path.
A minimum priority queue can be used to efficiently receive the vertex with least
path distance. function 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)
if tempDistance < distance[V]
distance[V]tempDistance
previous[V] U
return distance[], previous[]
Breadth First Search (BFS) algorithm traverses a graph in a breadth ward motion
and uses a queue to remember to get the next vertex to start a search, when a dead
• Rule 1 − Visit the adjacent unvisited vertex. Mark it as visited. Display it. Insert it in
a queue.
• Rule 2 − If no adjacent vertex is found, remove the first vertex from the queue.
7
From A we have D as
unvisited adjacent node. We
mark it as visited and
enqueue it.
BFS pseudocode
create a queue Q
The time complexity of the BFS algorithm is represented in the form of O(V +
E), where V is the number of nodes and E is the number of edges.
Depth First Search (DFS) algorithm traverses a graph in a depth ward motion and
uses a stack to remember to get the next vertex to start a search, when a dead end
occurs in any iteration.
• Rule 1 − Visit the adjacent unvisited vertex. Mark it as visited. Display it. Push it in
a stack.
• Rule 2 − If no adjacent vertex is found, pop up a vertex from the stack. (It
will pop up all the vertices from the stack, which do not have adjacent
vertices.)
• Rule 3 − Repeat Rule 1 and Rule 2 until the stack is empty.
5
We choose B, mark it as
visited and put onto the stack.
Here B does not have any
unvisited adjacent node. So,
we pop B from the stack.
6
We check the stack top for
return to the previous node
and check if it has any
unvisited nodes. Here, we
find D to be on the top of the
stack.
We can say that a graph G is a bi-connected graph if it is connected, and there are
no articulation points or cut vertex are present in the graph.
A graph is biconnected if it is connected and does not have any articulation points.
An articulation point is a vertex whose removal disconnects the graph.
Articulation Points:
Articulation points are vertices that, when removed, increase the number of
connected components in the graph. In a biconnected graph, there are no articulation
points.
Biconnected Components:
A biconnected component of a graph is a maximal subgraph that is itself
biconnected. In other words, within a biconnected component, any two vertices are
connected by at least two disjoint paths.
Biconnected Graphs vs. Biconnected Components:
A biconnected graph is a graph that has no articulation points, while a biconnected
component is a maximal subgraph within a graph that is itself biconnected.
Applications:
Biconnectivity has applications in network design, fault-tolerant communication
networks, and routing algorithms. It ensures that a network remains connected even
if certain nodes fail.
A bridge in a graph is an edge whose removal increases the number of connected
components. Bridges are closely related to biconnectivity, and the identification of
bridges is often part of algorithms for biconnectivity.
Network Reliability:
Biconnectivity is essential for ensuring the reliability of communication networks.
It helps in designing networks that can withstand the failure of individual
components without becoming disconnected.
Connectivity Maintenance:
Biconnectivity is crucial in scenarios where maintaining connectivity is vital, such
as in transportation networks, computer networks, and power grids.
Planarity:
Biconnectivity is related to the planarity of graphs. A biconnected planar graph has
certain properties that make it useful in various applications, including circuit
design.
PSEUDOCODE :
procedure findBiconnectedComponents(graph):
// Initialize variables
time = 0
stack = empty stack
result = empty list of biconnected components
visited = empty set of vertices
low = empty dictionary to store low values for vertices
parent = empty dictionary to store parent vertices in DFS tree
isArticulationPoint = empty set of vertices
// Function to perform DFS and find biconnected components
function DFS(u):
nonlocal time
time = time + 1
low[u] = time
visited.add(u)
stack.push(u)
for each v in graph[u]:
if v is not visited:
parent[v] = u
DFS(v)
low[u] = min(low[u], low[v])
// Check for articulation points
if low[v] >= low[u]:
if u is in stack:
biconnectedComponent = []
while stack is not empty and stack.top() != u:
biconnectedComponent.add(stack.pop())
biconnectedComponent.add(stack.pop())
result.add(biconnectedComponent)
else if v is not parent[u]:
low[u] = min(low[u], low[v])
// Perform DFS on each unvisited vertex
for each vertex in graph:
if vertex is not visited:
DFS(vertex)
// Output the biconnected components
print("Biconnected Components:")
for each component in result:
print(component)
12. How do you compute maximum flow for the following graph using
Ford-Fulkerson method? (MAY 2015) (E)
Network Flow
Flow Network is a directed graph that is used for modeling material
Flow. There are two different vertices; one is a source which produces
material at some steady rate, and another one is sink which consumes
the content at the same constant speed. The flow of the material at any
mark in the system is the rate at which the element moves.
Some real-life problems like the flow of liquids through pipes, the
current through wires and delivery of goods can be modelled using
flow networks.
Definition: A Flow Network is a directed graph G = (V, E) such that
1. For each edge (u, v) ∈ E, we associate a nonnegative weight
capacity c (u, v) ≥ 0.If (u, v) ∉ E, we assume that c (u, v) = 0.
2. There are two distinguishing points, the source s, and the sink t;
3. For every vertex v ∈ V, there is a path from s to t containing v.
Let G = (V, E) be a flow network. Let s be the source of the network,
and let t be the sink. A flow in G is a real-valued function f: V x V→R
such that the following properties hold:
o Capacity Constraint: For all u, v ∈ V, we need f (u, v) ≤ c (u, v).
o Skew Symmetry: For all u, v ∈ V, we need f (u, v) = - f (u, v).
FORD-FULKERSON (G, s, t)
1. for each edge (u, v) ∈ E [G]
2. do f [u, v] ← 0
3. f [u, v] ← 0
4. while there exists a path p from s to t in the residual network Gf.
5. do cf (p)←min?{ Cf (u,v):(u,v)is on p}
6. for each edge (u, v) in p
7. do f [u, v] ← f [u, v] + cf (p)
8. f [u, v] ←-f[u,v]