Unit 2 Algorithm

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 39

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
PART A
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.
Example:
V1 V2

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:

4. What is sub graph? V V

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 Graph G’ Sub Graph


5. What is connected graph?

An directed graph is said to be connected if for every pair of distinct


vertices Vi 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

V3
(v1,v2) ≠ (v2,v1)

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

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

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

V4
V2
V3
V5

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

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

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 are the different kinds of graph traversals?

• Depth-first traversal

• Breadth-first traversal
15. 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).
Degree (A) = 0
Degree (C) = 1
Degree (D) = 3
16. 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.

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


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

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

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

21. What is unweighted shortest path?

The unweighted shortest path is the path in unweighted graph which is


equal to number of edges traveled from source to destination.
S.No Path Number of edges

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

22. What are the different kinds of graph traversals?

• Depth-first traversal

• Breadth-first traversal

23. 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.
Example:

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

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


25.What is biconnectivity?

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)

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.

31.Give the Floyd’s algorithm (Nov 17)


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
sequence of expanding subtrees. The initial subtree in such a sequence
consists of a single vertex 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 to it 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. (MAY
2015)
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 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.

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 minheaps 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 it is 0.

37.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 of finding a
maximum matching in a given graph. For an arbitrary graph, this is rather
difficult problem. It was solved in 1965 by Jack Edmonds.

38.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 graph
with the illustration above shows some bipartite graphs, with vertices in each
graph colored based on to which of the two disjoint sets they belong.

39.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, an
ii) no two nodes on the left are assigned to the same node on the right

40. 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:
• 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.

41.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. Describe various ways in which graphs are represented.


A graph G(V, E) is a non-linear data structure that
consists of node and edge pairs of objects connected by
links.

There are 2 types of graphs:


• Directed
• Undirected
Directed graph
A graph with only directed edges is said to be a directed
graph. Example
The following directed graph has 5 vertices and 8 edges. This
graph G can be defined as G = (V, E), where V =
{A,B,C,D,E} and E = {(A,B), (A,C) (B, E), (B,D), (D, A),
(D, E),(C,D),(D,D)}.
Directed Graph
Undirected graph
A graph with only undirected edges is said to be an undirected
graph. Example
The following is an undirected graph.

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.

3. Protein-protein interactions graphs: Vertices represent


proteins and edges represent interactions between them
that carry out some biological function in the cell.
These graphs can be used to, for example, study
molecular pathway—chains of molecular interactions in
a cellular process.
4. Network packet traffic graphs: Vertices are IP (Internet
protocol) addresses and edges are the packets that flow
between them. Such graphs are used for analyzing
network security, studying the spread of worms, and
tracking criminal or non- criminal activity.
5. Neural networks: Vertices represent neurons and edges
are the synapses between them. Neural networks are
used to understand how our brain works and how
connections change when we learn. The human brain has
about 1011 neurons and close to 1015 synapses.

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

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

Start with a weighted graph

Choose a vertex

Choose the shortest edge from this vertex and add it

Choose the nearest vertex not yet in the solution

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.

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

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


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)}
UNION(u, v)
return A

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.

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

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

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[]

Dijkstra's Algorithm Complexity


Time Complexity: O(E Log V)
where, E is the number of edges and V is the number
of vertices. Space Complexity: O(V)

8. Explain Breadth – First Search.

Breadth First Search

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

end occurs in any iteration.

As in the example given above, BFS algorithm traverses from A to B to E to F


first then to C and G lastly to D. It employs the following rules.

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

• Rule 3 − Repeat Rule 1 and Rule 2 until the queue is empty.


Step Traversal Description

Initialize the queue.

We start from visiting S


(starting node), and mark it as
visited.

3 We then see an unvisited


adjacent node from S. In this
example, we have three nodes
but alphabetically we choose
A, mark it as visited and
enqueue it.

Next, the unvisited adjacent


node from S is B. We mark it
as visited and enqueue it.

Next, the unvisited adjacent


node from S is C. We mark it
as visited and enqueue it.

Now, S is left with no


unvisited adjacent nodes. So,
we dequeue and find A.

7
From A we have D as
unvisited adjacent node. We
mark it as visited and
enqueue it.

BFS pseudocode

create a queue Q

mark v as visited and put v into Q while Q is non-empty


remove the head u of Q

mark and enqueue all (unvisited) neighbours of u

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


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
9. Explain depth first search on a graph with necessary data structures.
DFS – Depth First Search

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.

As in the example given above, DFS algorithm traverses from S to A to D to G


to E to B first, then to F and lastly to C. It employs the following rules.

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

Step Traversal Description


1

Initialize the stack.

2 Mark S as visited and put it onto


the stack. Explore any unvisited
adjacent node from S. We have
three nodes and we can pick any
of them. For this example, we
shall take the node in an
alphabetical order.

3 Mark A as visited and put it


onto the stack. Explore any
unvisited adjacent node from
A. Both S and D are adjacent
to A but we are concerned for
unvisited nodes only.

4 Visit D and mark it as visited and


put onto the stack. Here, we
have B and C nodes, which are
adjacent to D and both are
unvisited. However, we shall
again choose in an
alphabetical order.

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.

Only unvisited adjacent node is


from D is C now. So we visit
C, mark it as visited and put it
onto the stack.
Application of DFS Algorithm

1. For finding the path

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

10. Write short notes on Biconnectivity Graph?


Bi Connectivity Graph

An undirected graph is said to be a biconnected graph, if there are two


vertex-disjoint paths between any two vertices are present. In other
words, we can say that there is a cycle between any two vertices.

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)

11.Explain the algorithm for Maximum Bipartite Matching.


Maximum Bipartite Matching
The bipartite matching is a set of edges in a graph is chosen in such a
way, that no two edges in that set will share an endpoint. The maximum
matching is matching the maximum number of edges.

When the maximum match is found, we cannot add another edge. If


one edge is added to the maximum matched graph, it is no longer a
matching. For a bipartite graph, there can be more than one maximum
matching is possible.
Algorithm
bipartiteMatch(u, visited, assign)
Input: Starting node, visited list to keep track, assign the list to assign node with
another node.
Output − Returns true when a matching for vertex u is possible.
Begin
for all vertex v, which are
adjacent with u, do if v is
not visited, then
mark v as visited
if v is not assigned, or bipartiteMatch(assign[v], visited,
assign) is true, then assign[v] := u
return true done
return false End
maxMatch(graph) Input − The given graph.
Output − The maximum number of the match.
Begin
initially no vertex is assigned count := 0
for all applicant u in M, do make all node as unvisited
if bipartiteMatch(u, visited, assign),
then increase count by 1
done
End

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

o Flow Conservation: For all u ∈ V-{s, t}, we need

The quantity f (u, v), which can be positive or negative, is known as


the net flow from vertex u to vertex v. In the maximum-flow problem,
we are given a flow network G with source s and sink t, and
a flow of maximum value from s to t.
Ford-Fulkerson Algorithm
Initially, the flow of value is 0. Find some augmenting Path p and
increase flow f on each edge of p by residual Capacity cf (p). When no
augmenting path exists, flow f is a maximum flow.
FORD-FULKERSON METHOD (G, s, t)
1. Initialize flow f to 0
2. while there exists an augmenting path p
3. do argument flow f along p
4. Return f

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]

You might also like