Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 34

SRRCET/CSE/IV SEMESTER/CS3401-ALGORITHM

UNIT II

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

1. Define a graph. (April/May 2007)


A graph G=(V, E) consists of a set of vertices(V) and set of edges(E).

In general, A graph is a collection of nodes (also called vertices) and edges (also called
arcs or links) each connecting a pair of nodes.
V1 V2
Example:

V3
2. What are the different types of Graph?
There are two types of Graphs. They are:

1. Directed Graphs.
2. Undirected Graphs.
Example for Directed Graph: Example for undirected Graph:

3. What is complete graph?


If an undirected graph of n vertices consists of n(n-1)/2 number of edges it is called as
complete graph.
V1
V
Example:

V V

PREPARED BY D.SUJATHA, AP/CSE Page 1


SRRCET/CSE/IV SEMESTER/CS3401-ALGORITHM

4. What is sub graph?


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

G Grapth G’ Sub Graph

5. What is connected graph?


An directed graph is said to be connected if for every pair of distinct vertices V i and
Vj in V(G) there is a graph from Vi to Vj in G.

Example: V1 V2

V3 V4
6. What are directed graphs?
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

(v1,v2) ≠ (v2,v1)

V3

PREPARED BY D.SUJATHA, AP/CSE Page 2


SRRCET/CSE/IV SEMESTER/CS3401-ALGORITHM

7. What are undirected graphs?


An undirected graph is a graph, which consists of undirected edges. If (v,w) is an
undirected edge then (v,w) = (w,v)

V V

(v1,v2) = (v2,v1)
V
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 graph which has a cycle is referred to as cyclic graph.

9. Define Acyclic graph.


A directed graph is said to be acyclic when there is no cycle path in it. It is also called
DAG(Directed Acyclic Graph).

Example Path: A -> C -> D


A

B C

D E

10. Define weighted graph.


A graph is said to be weighted graph if every edge in the graph is assigned a weight
or value. It can be directed or undirected graph.

PREPARED BY D.SUJATHA, AP/CSE Page 3


SRRCET/CSE/IV SEMESTER/CS3401-ALGORITHM

Ex:
1 1
1 2
1 2
2 2
2 2

3 3

11. Define strongly connected graph.


A directed graph is said to be strongly connected, if for every pair of vertex, there
exists a path

Diagram: V1 V2

V4 V5
V5

12. What is weakly connected graph. (May/June 2012)


A digraph is weakly connected if all the vertices are connected to each other.

Diagram: V5 V1 V2

V4 V3

PREPARED BY D.SUJATHA, AP/CSE Page 4


SRRCET/CSE/IV SEMESTER/CS3401-ALGORITHM

13. Define path in a graph.


A path in a graph is a sequence of vertices such that from each of its vertices there is
an edge to the next vertex in the sequence. A path may be infinite, but a finite path always
has a first vertex, called its start vertex, and a last vertex, called its end vertex. Both of
them are called end or terminal vertices of the path. The other vertices in the path are
internal vertices. A cycle is a path such that the start vertex and end vertex are the same.

14. What is the degree of a graph?


The number of edges incident on a vertex determines its degree. The degree of the
vertex V is written as degree(V).

Example: A C

B D

Degree (A) = 0

Degree (C) = 1

Degree (D) = 3

15. Define indegree, outdegree in a graph. (April/May 2010)


The indegree is the numbers of edges entering in to the vertex V.

The out degree is the numbers of edges that are exiting or leaving from the vertex V.

Indegree(V1) = 1,Outdegree(V1)=2
V1 V,

V3

PREPARED BY D.SUJATHA, AP/CSE Page 5


SRRCET/CSE/IV SEMESTER/CS3401-ALGORITHM

16. What is adjacent node?


Adjacency node is the node which is connected to the other nodes in the graph.

Example:
A C

B D

In the above diagram, C is an adjacent node to E

17. What are the applications of graphs?


The various applications of graphs are:
 In computer networking such LAN, WAN etc., internetworking of computer systems is
done using graph concept.
 In telephone cabling, graph theory is effectively used.
 In job scheduling algorithms, the graph is
used. Solution: a b c d

18. 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

No. of vertices = 2 Degree = 3 No. of vertices = 4

This implies that the no. of vertices is even for odd degree graphs.

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. What is unweighted shortest path?


The unweighted shortest path is the path in unweighted graph which is equal to
PREPARED BY D.SUJATHA, AP/CSE Page 6
SRRCET/CSE/IV SEMESTER/CS3401-ALGORITHM

number of edges traveled from source to destination.

Example:
V V

aV V V V V z

V V V
The paths from a to z are as below:

S.No Path Number


of edges
1 V1-V2- 3
V3-
2 V1-V4- 4
V5-
3 V1-V7- 4
V8-
V1-V2-V3-V10 is the shortest path.

21. What are the different kinds of graph traversals?


 Depth-first traversal
 Breadth-first traversal

22. What is depth-first traversal? Give an example.


Depth-first search (DFS) is a graph search algorithm that begins at the root and
explores as far as possible along each branch before backtracking.
Note: Backtracking is finding a solution by trying one of several choices. If the choice
proves incorrect, computation backtracks or restarts at the point of choice and tries
another choice. 1

Example:
2 3

The Depth-first traversal is 1 – 2 – 4 – 3 4

PREPARED BY D.SUJATHA, AP/CSE Page 7


SRRCET/CSE/IV SEMESTER/CS3401-ALGORITHM

23. What is breadth-first traversal? Give an example.


Breadth-first search (BFS) is a graph search algorithm that begins at the root node
and explores all the neighboring nodes. Then for each of those nearest nodes, it explores
their unexplored neighbor nodes, and so on, until it finds the goal.

Example:
1

2 3

The breadth-first Traversal is 1 – 2 – 3 – 4

24. What is biconnectivity?


Biconnected graphs are the graphs which cannot be broken into two disoconnected
graphs by disconnecting single edge.

Example

In the given example, after removing edge E1 the graph does not become disconnected.

25. 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)

26. Define prims algorithm.

Prim's Algorithm is a greedy algorithm that is used to find the minimum spanning tree
from a graph. Prim's algorithm finds the subset of edges that includes every vertex of the

PREPARED BY D.SUJATHA, AP/CSE Page 8


SRRCET/CSE/IV SEMESTER/CS3401-ALGORITHM

graph such that the sum of the weights of the edges can be minimized.

Prim's algorithm starts with the single node and explores all the adjacent nodes with all
the connecting edges at every step. The edges with the minimal weights causing no cycles
in the graph got selected.

27. Define Kruskal algorithm.

Kruskal's Algorithm is used to find the minimum spanning tree for a connected
weighted graph. The main target of the algorithm is to find the subset of edges by using
which we can traverse every vertex of the graph. It follows the greedy approach that finds
an optimum solution at every stage instead of focusing on a global optimum.

28. Define Bellman Ford algorithm.

Bellman Ford algorithm helps us find the shortest path from a vertex to all other vertices
of a weighted graph.It can work with graphs in which edges can have negative weights.

29. Define Dijkstra’s algorithm.

Dijkstra's Algorithm finds the shortest path between a given node (which is called the
"source node") and all other nodes in a graph.This algorithm uses the weights of the
edges to find the path that minimizes the total distance (weight) between the source node
and all other nodes.

30. Define Floyd-Warshall algorithm.

The all pair shortest path algorithm is also known as Floyd-Warshall algorithm is used to
find all pair shortest path problem from a given weighted graph. As a result of this
algorithm, it will generate a matrix, which will represent the minimum distance from any
node to all other nodes in the graph.

At first the output matrix is same as given cost matrix of the graph. After that the output
matrix will be updated with all vertices k as the intermediate vertex.
PREPARED BY D.SUJATHA, AP/CSE Page 9
SRRCET/CSE/IV SEMESTER/CS3401-ALGORITHM

31. Give the Floyd’s algorithm


ALGORITHM Floyd(W[1..n,1..n])
//Implements Floyd’s algorithm for the all-pair shortest–path problem
//Input The weight matrix W of a graph
//Output The distance matrix of the shortest paths’ lengths
D <- W
for k = 1 to n do
for i =1 to n do
for j =1 to n do
D[I,j] = min{D[I,j], D[I,k] + D[k,j]

32. Define Prims Algorithm.


Prim’s algorithm constructs a minimum spanning tree through a sequenceof
expanding subtrees. The initial subtree in such a sequence consists of a singlevertex
selected arbitrarily from the set V of the graph’s vertices. On each iteration,the algorithm
expands the current tree in the greedy manner by simply attaching toit the nearest vertex
not in that tree.

33. Write down the optimization technique used for Warshalls algorithm. State
the rules and assumptions which are implied behind that.
Warshalls algorithm constructs the transitive closure of given digraph with n
vertices through a series of n-by-n Boolean matrices. The computations in warshalls
algorithm are given by following sequences,

R(0),…,R(k-1),…,R(k),…,R(n)

Rules:
1. Start with computation of R (0). In R(0) any path with intermediate veritices 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

PREPARED BY D.SUJATHA, AP/CSE Page 10


SRRCET/CSE/IV SEMESTER/CS3401-ALGORITHM

of given digraph.

34. Define the single source shortest path problem. (MAY\JUNE 2016)
Dijkstra’s algorithm solves the single source shortest path problem of finding
shortest paths from a given vertex( the source), to all the other vertices of a weighted
graph or digraph.
Dijkstra’s algorithm provides a correct solution for a graph with non-negative weights.

35. How to calculate the efficiency of dijkstra’s algorithm. (NOV/DEC 16)


The time efficiency depends on the data structure used for implementing the
priority queue and for representing the input graph. It is in θ (|V|)2 for graphs represented
by their weight matrix and the priority queue implemented as an unordered array. For
graphs represented by their adjacency linked lists and the priority queue implemented as
a min_heap it is in O(|E|log|V|).

36. Define transitive closure of a directed graph. (APR/MAY 2018)


The transitive closure of a directed graph with n vertices can be defined as the “n-
by-n” Boolean matrix T={tij} in which,the element in the ith row (1<i<n) and the jth
column (1<j<n) exists a non-trival directed path from the Ith vertex to the jth
vertex,otherwise tij is 0.

37. Write short notes on the Maximum-Flow problem.


Maximum-flow algorithms require processing edges in both directions, it is
convenient to modify the adjacency matrix representation of a network as follows. If
there is a directed edge from vertex i to vertex j of capacity uij ,then the element in the ith
row and the jth column is set to uij , and the element in the jth row and the ith column is

set to −uij; if there is no edge between vertices i and j , both these elements are set to
zero. Outline a simple algorithm for identifying a source and a sink in a network
presented by sucha matrix and indicate its time efficiency.

38. Define maximum matching.


In many situations we are faced with a problem of pairing elements of two
sets.The traditional example is boys and girls for a dance, but you can easily thinkof more
serious applications. It is convenient to represent elements of two givensets by vertices of
a graph, with edges between vertices that can be paired. Amatching in a graph is a subset
of its edges with the property that no two edgesshare a vertex. A maximum matching—
more precisely, a maximum cardinalitymatching—is a matching with the largest number

PREPARED BY D.SUJATHA, AP/CSE Page 11


SRRCET/CSE/IV SEMESTER/CS3401-ALGORITHM

of edges.

39. Define maximum cardinality. (NOV/DEC 2016) (Apr 18)


Maximum cardinality matching—is a matching with the largest number of edges.
The maximum-matching problem is the problem offinding a maximum matching in a
given graph. For an arbitrary graph, this is arather difficult problem. It was solved in
1965 by Jack Edmonds.

40. Define maximum flow problem.


The maximum flow problem can be seen as a special case of more complex
network flow problems, such as the circulation problem. The maximum value of an s-t
flow (i.e., flow from source s to sink t) is equal to the minimum capacity of an s-t cut
(i.e., cut severing s from t) in the network, as stated in the max-flow min-cut theorem.

41. Define Bipartite Graphs? (Nov 17)


A bipartite graph, also called a bigraph, is a set of graph vertices decomposed into
two disjoint sets such that no two graph vertices within the same set are adjacent. A
bipartite graph is a special case of a k-partite graphwith . The illustration above
shows some bipartite graphs, with vertices in each graph colored based on to which of the
two disjoint sets they belong.

42. What do you meant by perfect matching in bipartite graph? (APR/MAY 2017)
When there are an equal number of nodes on each side of a bipartite graph, a
perfect matching is an assignment of nodes on the left to nodes on the right, in such a way
that
i) each node is connected by an edge to the node it is assigned to, and

ii) no two nodes on the left are assigned to the same node on the right

43. Define flow cut. (R)


Cut is a collection of arcs such that if they are removed there is no path from s to
t. A cut is said to be minimum in a network whose capacity is minimum over all cuts of
the network.

44. How is a transportation network represented? (APR/MAY 18)

The transportation network can be represented by a connected weighted digraph with


n vertices numbered from 1 to n and a set of edges E, with the following properties:

PREPARED BY D.SUJATHA, AP/CSE Page 12


SRRCET/CSE/IV SEMESTER/CS3401-ALGORITHM

 It contains only one vertex with no entering edges called as source and assumed to be 1.
 It contains only one vertex at end with no leaving edges called as sink and assumed as n.
 The weight uij of each directed edge (i, j) is a positive integer, called as edge capacity.

45. Define the constraint in the context of maximum flow problem. (APR/MAY 2019)
It represents the maximum amount of flow that can pass through an edge. ... , for each
(capacity constraint: the flow of an edge cannot exceed its capacity); , for each
(conservation of flows: the sum of the flows entering a node must equal the sum of
the flows exiting a node, except for the source and the sink nodes).

PART-B

1. Explain breadth first traversal method for graph with algorithm.


Breadth first search
Traversal means visiting all the nodes of a graph. Breadth First Traversal or Breadth First Search is a
recursive algorithm for searching all the vertices of a graph or tree data structure.

BFS algorithm

A standard BFS implementation puts each vertex of the graph into one of two categories:

1. Visited

2. Not Visited

The purpose of the algorithm is to mark each vertex as visited while avoiding cycles.

The algorithm works as follows:

1. Start by putting any one of the graph's vertices at the back of a queue.

2. Take the front item of the queue and add it to the visited list.

3. Create a list of that vertex's adjacent nodes. Add the ones which aren't in the visited list to the back of the
queue.

4. Keep repeating steps 2 and 3 until the queue is empty.

PREPARED BY D.SUJATHA, AP/CSE Page 13


SRRCET/CSE/IV SEMESTER/CS3401-ALGORITHM

The graph might have two different disconnected parts so to make sure that we cover every vertex, we can
also run the BFS algorithm on every node

BFS example

Let's see how the Breadth First Search algorithm works with an example. We use an undirected graph with
5 vertices.

Undirected graph with 5 vertices


We start from vertex 0, the BFS algorithm starts by putting it in the Visited list and putting all its adjacent
vertices in the stack.

Visit start vertex and add its adjacent vertices to queue


Next, we visit the element at the front of queue i.e. 1 and go to its adjacent nodes. Since 0 has already been
visited, we visit 2 instead.

Visit the first neighbour of start node 0, which is 1


Vertex 2 has an unvisited adjacent vertex in 4, so we add that to the back of the queue and visit 3, which is
at the front of the queue.

PREPARED BY D.SUJATHA, AP/CSE Page 14


SRRCET/CSE/IV SEMESTER/CS3401-ALGORITHM

Visit 2 which was added to queue earlier to add its neighbours

4 remains in the queue


Only 4 remains in the queue since the only adjacent node of 3 i.e. 0 is already visited. We visit it.

Visit last remaining item in the queue to check if it has unvisited neighbors

Since the queue is empty, we have completed the Breadth First Traversal of the graph.

BFS Algorithm Complexity

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.
The space complexity of the algorithm is O(V).

BFS Algorithm Applications

1. To build index by search index

PREPARED BY D.SUJATHA, AP/CSE Page 15


SRRCET/CSE/IV SEMESTER/CS3401-ALGORITHM

2. For GPS navigation

3. Path finding algorithms

4. In Ford-Fulkerson algorithm to find maximum flow in a network

5. Cycle detection in an undirected graph

6. In minimum spanning tree

2. Explain depth first traversal method for graph with algorithm.

Depth First Search (DFS)

Depth first Search or Depth first traversal is a recursive algorithm for searching all the vertices of a graph or
tree data structure. Traversal means visiting all the nodes of a graph.

Depth First Search Algorithm

A standard DFS implementation puts each vertex of the graph into one of two categories:

1. Visited

2. Not Visited

The purpose of the algorithm is to mark each vertex as visited while avoiding cycles.

The DFS algorithm works as follows:

1. Start by putting any one of the graph's vertices on top of a stack.

2. Take the top item of the stack and add it to the visited list.

3. Create a list of that vertex's adjacent nodes. Add the ones which aren't in the visited list to the top of the
stack.

4. Keep repeating steps 2 and 3 until the stack is empty.

Depth First Search Example

PREPARED BY D.SUJATHA, AP/CSE Page 16


SRRCET/CSE/IV SEMESTER/CS3401-ALGORITHM

Let's see how the Depth First Search algorithm works with an example. We use an undirected graph with 5
vertices.

Undirected graph with 5 vertices


We start from vertex 0, the DFS algorithm starts by putting it in the Visited list and putting all its adjacent
vertices in the stack.

Visit the element and put it in the visited list


Next, we visit the element at the top of stack i.e. 1 and go to its adjacent nodes. Since 0 has already been
visited, we visit 2 instead.

Visit the element at the top of stack


Vertex 2 has an unvisited adjacent vertex in 4, so we add that to the top of the stack and visit it.

PREPARED BY D.SUJATHA, AP/CSE Page 17


SRRCET/CSE/IV SEMESTER/CS3401-ALGORITHM

Vertex 2 has an unvisited adjacent vertex in 4, so we add that to the top of the stack and visit it.

Vertex 2 has an unvisited adjacent vertex in 4, so we add that to the top of the stack and visit it.
After we visit the last element 3, it doesn't have any unvisited adjacent nodes, so we have completed the
Depth First Traversal of the graph.

After we visit the last element 3, it doesn't have any unvisited adjacent nodes, so we have completed the
Depth First Traversal of the graph.

Complexity of Depth First Search

The time complexity of the DFS algorithm is represented in the form of O(V + E), where V is the number
of nodes and E is the number of edges.
The space complexity of the algorithm is O(V).
Application of DFS Algorithm
1. For finding the path

PREPARED BY D.SUJATHA, AP/CSE Page 18


SRRCET/CSE/IV SEMESTER/CS3401-ALGORITHM

2. To test if the graph is bipartite

3. For finding the strongly connected components of a graph

4. For detecting cycles in a graph


3. Explain the Dijkstra’s shortest path algorithm and its efficiency.

Dijkstra's Algorithm:

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.

PREPARED BY D.SUJATHA, AP/CSE Page 19


SRRCET/CSE/IV SEMESTER/CS3401-ALGORITHM

Start with a weighted graph

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

PREPARED BY D.SUJATHA, AP/CSE Page 20


SRRCET/CSE/IV SEMESTER/CS3401-ALGORITHM

Avoid updating path lengths of already visited vertices

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

Repeat until all the vertices have been visited


PREPARED BY D.SUJATHA, AP/CSE Page 21
SRRCET/CSE/IV SEMESTER/CS3401-ALGORITHM

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.

4. Write floyd’s algorithm to find all pair shortest path and derive its complexity.

Floyd-Warshall Algorithm

Floyd-Warshall Algorithm is an algorithm for finding the shortest path between all the pairs of vertices in a
weighted graph. This algorithm works for both the directed and undirected weighted graphs. But, it does not
work for the graphs with negative cycles (where the sum of the edges in a cycle is negative).

A weighted graph is a graph in which each edge has a numerical value associated with it.

Floyd-Warhshall algorithm is also called as Floyd's algorithm, Roy-Floyd algorithm, Roy-Warshall


algorithm, or WFI algorithm.

This algorithm follows the dynamic programming approach to find the shortest paths.

How Floyd-Warshall Algorithm Works?

Let the given graph be:

Initial graph
Follow the steps below to find the shortest path between all the pairs of vertices.

PREPARED BY D.SUJATHA, AP/CSE Page 22


SRRCET/CSE/IV SEMESTER/CS3401-ALGORITHM

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.


2. Fill each cell with the distance between ith and jth vertex
3. 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 through 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 k.
4. 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.

PREPARED BY D.SUJATHA, AP/CSE Page 23


SRRCET/CSE/IV SEMESTER/CS3401-ALGORITHM

5. 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 2.

6. Calculate the distance from the source vertex to destination vertex through this vertex 2
7. Similarly, A3 and A4 is also created.

8. Calculate the distance from the source vertex to destination vertex through this vertex

3
9. Calculate the distance from the source vertex to destination vertex through this vertex 4
10. 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

PREPARED BY D.SUJATHA, AP/CSE Page 24


SRRCET/CSE/IV SEMESTER/CS3401-ALGORITHM

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

Floyd Warshall Algorithm Complexity

Time Complexity

There are three loops. Each loop has constant complexities. So, the time complexity of the Floyd-Warshall
algorithm is O(n3).
Space Complexity

The space complexity of the Floyd-Warshall algorithm is O(n2).

Floyd Warshall Algorithm Applications

 To find the shortest path is a directed graph

 To find the transitive closure of directed graphs

 To find the Inversion of real matrices

 For testing whether an undirected graph is bipartite

5. Explain kruskal’s algorithm with suitable Example

Kruskal's 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

PREPARED BY D.SUJATHA, AP/CSE Page 25


SRRCET/CSE/IV SEMESTER/CS3401-ALGORITHM

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.

4. Example of Kruskal's algorithm

Start with a weighted graph

Choose the edge with the least weight, if there are more than 1, choose anyone

Choose the next shortest edge and add it

PREPARED BY D.SUJATHA, AP/CSE Page 26


SRRCET/CSE/IV SEMESTER/CS3401-ALGORITHM

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

Repeat until you have a spanning tree

Kruskal Algorithm Pseudocode

Any minimum spanning tree algorithm revolves around checking if adding an edge creates a loop or not.

The most common way to find this out is an algorithm called Union Find. The Union-Find algorithm
divides the vertices into clusters and allows us to check if two vertices belong to the same cluster or not and
hence decide whether adding an edge creates a cycle.

KRUSKAL(G):
A=∅
For each vertex v ∈ G.V:
MAKE-SET(v)
For each edge (u, v) ∈ G.E ordered by increasing order by weight(u, v):
if FIND-SET(u) ≠ FIND-SET(v):
A = A ∪ {(u, v)}

PREPARED BY D.SUJATHA, AP/CSE Page 27


SRRCET/CSE/IV SEMESTER/CS3401-ALGORITHM

UNION(u, v)
return A

Kruskal's vs Prim's Algorithm

Prim's algorithm is another popular minimum spanning tree algorithm that uses a different logic to find the
MST of a graph. Instead of starting from an edge, Prim's algorithm starts from a vertex and keeps adding
lowest-weight edges which aren't in the tree, until all vertices have been covered.

Kruskal's Algorithm Complexity

The time complexity Of Kruskal's Algorithm is: O(E log E).

Kruskal's Algorithm Applications

 In order to layout electrical wiring

 In computer network (LAN connection)


6. Explain briefly ford fulkerson method with suitable example

Ford-Fulkerson Algorithm

Ford-Fulkerson algorithm is a greedy approach for calculating the maximum possible flow in a network or a
graph.
A term, flow network, is used to describe a network of vertices and edges with a source (S) and a sink (T).
Each vertex, except S and T, can receive and send an equal amount of stuff through it. S can only send
and T can only receive stuff.
We can visualize the understanding of the algorithm using a flow of liquid inside a network of pipes of
different capacities. Each pipe has a certain capacity of liquid it can transfer at an instance. For this
algorithm, we are going to find how much liquid can be flowed from the source to the sink at an instance
using the network.

PREPARED BY D.SUJATHA, AP/CSE Page 28


SRRCET/CSE/IV SEMESTER/CS3401-ALGORITHM

Flow network graph

Terminologies Used

Augmenting Path

It is the path available in a flow network.

Residual Graph

It represents the flow network that has additional possible flow.

Residual Capacity

It is the capacity of the edge after subtracting the flow from the maximum capacity.

How Ford-Fulkerson Algorithm works?

The algorithm follows:

1. Initialize the flow in all the edges to 0.

2. While there is an augmenting path between the source and the sink, add this path to the flow.

3. Update the residual graph.

We can also consider reverse-path if required because if we do not consider them, we may never find a
maximum flow.

The above concepts can be understood with the example below.

Ford-Fulkerson Example

PREPARED BY D.SUJATHA, AP/CSE Page 29


SRRCET/CSE/IV SEMESTER/CS3401-ALGORITHM

The flow of all the edges is 0 at the beginning.

Flow network graph example


1. Select any arbitrary path from S to T. In this step, we have selected path S-A-B-T.

The minimum capacity among the three edges is 2 ( B-T). Based on this, update the flow/capacity for each

path.
2. Select another path S-D-C-T. The minimum capacity among these edges is 3 ( S-D).

PREPARED BY D.SUJATHA, AP/CSE Page 30


SRRCET/CSE/IV SEMESTER/CS3401-ALGORITHM

3. Now, let us consider the reverse-path B-D as well. Selecting path S-A-B-D-C-T. The minimum residual

capacity among the edges is 1 (D-C).

The capacity for forward and reverse paths are considered separately.

4. Adding all the flows = 2 + 3 + 1 = 6, which is the maximum possible flow on the flow network.Note that if
the capacity for any edge is full, then that path cannot be used.

Ford-Fulkerson Applications

 Water distribution pipeline

 Bipartite matching problem

 Circulation with demands

PREPARED BY D.SUJATHA, AP/CSE Page 31


SRRCET/CSE/IV SEMESTER/CS3401-ALGORITHM

Review questions

1. Write an algorithm for all pairs shortest path algorithm and what are the time and space
complexity of the algorithm. (APIRL/MAY2009) (APRIL/MAY 2012)
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).

3. With a suitable example, explain all-pair shortest paths problem.


4. How do you construct a minimum spanning tree using Kruskals algorithm? Explain?(4)
(MAY 2015)

5. Discuss about the algorithm and pseudocode to find the Minimum Spanning Tree using
Prim’s Algorithm. Find the Minimum Spanning Tree for the graph. Discuss about the
efficiency of the algorithm.(MAY\JUNE 2016) (Apr 18)

6.Solve the all-Pairs shortest-path problem for the diagraph with the following weight

matrix: (NOV/DEC 2016)

7.Apply Kruskal’s algorithm to find a minimum spanning tree of the following graph.

(NOV/DEC 2016)

8.Write suitable ADT operation for shortest path problem. Show the simulation of shortest path
with an example graph.

9.Write short notes on Biconnectivity

PREPARED BY D.SUJATHA, AP/CSE Page 32


SRRCET/CSE/IV SEMESTER/CS3401-ALGORITHM

10.Explain Dijkstra’s algorithm using the following graph. Find the shortest path
between v1, v2, v3, v4, v5, v6 & v7. 2
(May/June 2007) V2
V1
4 1 3 10

2 7
V4
V3 V5

5 8 4 6

1 V6
V7

11.Explain the algorithm for Maximum Bipartite Matching.


12.How do you compute maximum flow for the following graph using
Ford-Fulkerson method? (MAY 2015)
u v

x y

13.State and Prove Maximum Flow Min cut Theorem. (MAY\JUNE 2016)
14.Apply the shortest Augmenting Path algorithm to the network shown
below.

15.Explain KMP string matching algorithm for finding a pattern on the text, a analysis
the algorithm.(APR/MAY 2017)
16.Determine the max-flow in the following network. (APR/MAY 2019)

PREPARED BY D.SUJATHA, AP/CSE Page 33


SRRCET/CSE/IV SEMESTER/CS3401-ALGORITHM

PREPARED BY D.SUJATHA, AP/CSE Page 34

You might also like