0% found this document useful (0 votes)
38 views40 pages

DAA Unit-III

The document discusses graphs and graph terminology. It defines what a graph is and different types of graphs like directed and undirected graphs. It also defines graph terminology like vertices, edges, paths, cycles, connected graphs and more.

Uploaded by

20981a4208
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
38 views40 pages

DAA Unit-III

The document discusses graphs and graph terminology. It defines what a graph is and different types of graphs like directed and undirected graphs. It also defines graph terminology like vertices, edges, paths, cycles, connected graphs and more.

Uploaded by

20981a4208
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 40

Graph Algorithms UNIT-3

GRAPHS
1. Introduction to Graphs
Why graphs are useful?
 Graphs are widely used to model any situation where entities or things are related to each other in
pairs; for example, the following information can be represented by graphs:
 Family trees in which the member nodes have an edge from parent to each of their children.
 Transportation networks in which nodes are airports, intersections, ports, etc. The edges can be
airline flights, one-way roads, shipping routes, etc.
What is a graph?
Graph: A graph, G, is a non-linear data structure represented as G = (V, E) consists of two sets, where
 V is a finite, nonempty set of vertices (also called nodes).
 E is a set of pairs of vertices; these pairs are called edges (or Arcs or links). Each edge ‘e’ in E is
identified with a unique pair (a, b) of nodes in V, denoted by e = (a, b).
 V (G) and E (G) will present the sets of vertices and edges, respectively, of G.
Example – 1:

Figure 1
Consider a graph, G in above Fig-1. Then the vertex V and edge E can be represented as:
V = {v1, v2, v3, v4, v5, v6} and E = {e1, e2, e3, e4, e5, e6} i.e., E = {(v1, v2) (v2, v3) (v1, v3) (v3, v4),
(v3, v5) (v5, v6)}. There are six edges and vertices in the graph.

Example –2:
The following is a graph with 5 vertices and 6 edges.
This graph G can be defined as G = ( V , E )
Where V = {A,B,C,D,E} and E = {(A,B),(A,C)(A,D),(B,D),(C,D),(B,E),(E,D)}.

Null graph (or Empty Graph): A graph G = (V, E) where E = , is called as a null or empty graph.
Trivial graph: A graph with one vertex and no edges is called a trivial graph
2. Graph Terminology
Vertex: A individual data element of a graph is called as Vertex. Vertex is also known as node. In above
example graph, A, B, C, D & E are known as vertices.
Edge: An edge is a connecting link between two vertices. Edge is also known as Arc. An edge is
represented as (startingVertex, endingVertex). For example, in above graph, the link between vertices A
and B is represented as (A, B). In above example graph, there are 7 edges (i.e., (A,B), (A,C), (A,D),
(B,D), (B,E), (C,D), (D,E)).
Types of graphs:
In general, graphs are classified as two types.

Blog: anilkumarprathipati.wordpress.com Page 1


Graph Algorithms UNIT-3

i) Undirected graph
ii) Directed graph (or digraph).
iii) Weighted graph
i. undirected graph:
In an undirected graph, the pair of vertices representing any edge is unordered (i.e., the edges of a graph
have no directions). Thus, the pairs (u, v) and (v, u) represent the same edge.

Undirected graph
This graph G can be defined as G = ( V , E )
Where V = {A,B,C,D,E} and E = {(A,B),(A,C)(A,D),(B,D),(C,D),(B,E),(E,D)}.
Two vertices are said to be adjacent if they are joined by an edge. If (u, v) is an edge in
E(G), then we say that the vertices u and v are adjacent and that the edge (u, v) is incident on vertices u
and v.
ii. directed graph:
In a directed graph, each edge is represented by a directed pair <u, v> (i.e., the edges of a graph have
directions); u is the tail and v the head of the edge. Therefore, <v, u> and <u, v> represent two different
edges.

G1 G2
Directed graph
This graph G can be defined as G1 = ( V , E )
Where V = {A,B,C,D,E} and E = {<A,B>,<A,D>, <B,D>, <C,B>,<D,E>,<E,C>}.
G2 = ( V , E ) where V = {a, b, c, d} and E = {<a, b>, <a, d>, <d, b>, <d, d>, <c, c>}
If edge (u, v) is a directed edge, then vertex u is adjacent to v, and v is adjacent from u.
The edge <u, v> is incident to u and v.

Blog: anilkumarprathipati.wordpress.com Page 2


Graph Algorithms UNIT-3

V(G1) = {0, 1, 2, 3}; E(G1) = {(0, 1), (0, 2), (0, 3), (1, 2), (1, 3), (2, 3)}
V(G2) = {0, 1, 2, 3, 4, 5, 6}; E(G2) = {(0, 1), (0, 2), (1, 3), (1, 4), (2, 5),(2, 6)}
V(G3) = {0, 1, 2 }; E(G3) = {<0, 1>, <1, 0>, <1, 2>}
Weighted graph:
Labeled graph or weighted graph: A graph is said to be labeled if every edge in the graph is assigned
some data.
A graph G is said to be weighted graph if every edge and/or vertices in the graph is
assigned with some weight or value. Weight of the edge, denoted by w(e) is a positive value which
indicates the cost of traversing the edge.
A weighted graph can be defined as G = (V, E, We, Wv) where V is the set of vertices, E is
the set at edges and We is a weights of the edges whose domain is E and Wv is a weight to the vertices
whose domain is V.

Weighted graphs
Consider a graph, which shows the distance in km between four metropolitan cities in India.
Here V = {N, K, M, C,} E = {(N, K), (N, M,), (M, K), (M, C), (K, C)} We = {55,47, 39, 27, 113}
and Wv = {N, K, M, C} The weight at the vertices is not necessary to maintain have become the set W v
and V are same. A graph with weighted edges is called a network.

Complete graph:
A graph G is said to be a complete, if all its nodes are fully connected, that is, there is a path from one
node to every other node in the graph.
An n vertex, undirected graph with exactly edges is said to be complete graph.
Let a and b are two vertices in the directed graph, then it is a complete graph if there is a path
from a to b as well as a path from b to a. An n vertex, directed graph with exactly n(n – 1) edges is said
to be complete digraph.
In the case of a digraph with n vertices, the maximum number of edges is given by nC2 = n(n–1).
Such a graph with exactly n(n – 1 ) edges is said to be a complete digraph.

Blog: anilkumarprathipati.wordpress.com Page 3


Graph Algorithms UNIT-3

Complete graph Complete digraph


Parallel/Multiple edges: Distinct edges which connect the same end points are called multiple edges
(i.e., a graph can have two or more edges connecting the same two vertices in the same direction). That is,
e = {u, v) and e’ = (u, v) are known as multiple edges of G.
Self – loop (or self – edge or loop): an edge that connects a vertex to itself. That is, e = (u, u).
Multi-graph: A graph with multiple edges and/or a loop is called a multi-graph. That is, A multi graph
G = (V, E) also consists of a set of vertices and edges except that E may contain multiple edges (i.e.)
edges connecting the same pair of vertices, or may contain loops or self-edges (i.e.) an edge whose end
points are the same vertex.

Simple (directed) graph: A directed graph G is said to be a simple (directed graph) if and only if it has
no parallel edges and loops. However, a simple directed graph may contain cycle with an exception that it
cannot have more than one loop at a given node.
A graph (digraph) that do not contain any cycle is called acyclic graph.
A directed graph that do not contain any cycles is called as directed acyclic graph (DAG).
Subgraph: A subgraph G’ = (V’,E’) of a graph G = (V, E) is such that V’ ⊆ V and E’ ⊆ E.

Graphs (a), (b) and (c) are the subgraph of G1

Blog: anilkumarprathipati.wordpress.com Page 4


Graph Algorithms UNIT-3

Path: A path between two vertices a and b in a graph is a sequence of vertices a, v1, v2,..., vn, b such that
all of the edges (a, v1), (v2, v3), ..., (vn, b) exist in the graph. In other words, a path is just what it sounds
like: a way to get from a to b possibly going through other vertices. The length of the path is the number
of edges on it.
A simple path is a path in which all the vertices except possibly the first and last vertices are distinct.
A cycle is a simple path in which the first and last vertices are the same. A cycle is also known as a
circuit, elementary cycle, circular path or polygon. A closed simple path with length 3 or more is known
as a cycle. A cycle of length k is called a k – cycle.
Two vertices vi, vj in a graph G are said to be connected only if there is a path in G between vi and vj
Acyclic graph and cyclic graph: If a graph does not contain any cycles, then the graph is called an
acyclic graph and if it contains cycle then the graph is cyclic.

An undirected graph is said to be a connected graph if every pair of distinct vertices vi , vj are
connected. That is to say that there are no isolated nodes in a connected graph.
In the case of an undirected graph which is not connected, the maximal connected subgraph is called as a
connected component or simply a component.

A directed graph is said to be strongly connected if every pair of distinct vertices vi, vj are connected (by
means of a directed path). That is, if u and v are two distinct vertices in V(G), there is a directed path
from u to v and also from v to u.
A strongly connected component is a maximal subgraph that is strongly connected.

The degree of a vertex is the number of edges incident to that vertex.


Blog: anilkumarprathipati.wordpress.com Page 5
Graph Algorithms UNIT-3

If G is a directed graph:
The in-degree of a vertex is the number of edges for which vertex is head (That is, the number of edges
coming towards vertex v).
And, the out-degree of a vertex is the number of edges for which the vertex is the tail (That is, the
number of edges leaving vertex v).
Degree of directed vertex(v) = in-degree(v) + out-degree(v)
For undirected graphs, there is no in-degree and out-degree; there is just the degree
If di is the degree of the vertex i in a graph with n vertices and e edges, then the number of edges is
e= / 2.
A vertex with degree one is called as a pendant vertex or end vertex (that is in-degree(v) = 1 and out-
degree(v) = 0).

V1 is a pendant vertex because it has an in-degree of 1 and out-degree of 0.


A vertex with degree zero and hence has no incident edges is called an isolated vertex.

Example: d is an isolated vertex in the given graph.


 A vertex v is called source if it has a +ve out-degree, but a zero in-degree.
 A vertex v is called sink if it has a +ve in-degree, but a zero out-degree.
 Size of the graph: The size of a graph is the total number of edges in it.
 Regular graph: Regular graph is a graph where each vertex has the same number of neighbors.
That is every node has the same degree. A regular graph with vertices of degree k is called a
k-regular graph or regular graph of degree k.
Example:

Blog: anilkumarprathipati.wordpress.com Page 6


Graph Algorithms UNIT-3

Two graphs are said to be isomorphic if,


 They have the same number of vertices.
 They have the same number of edges.
 They have an equal number of vertices with a given degree.

3. ADT for Graph


The abstract data type graph refers to all varieties of graphs, whether directed, undirected, weighted, or
unweighted.
AbstractDataType graph
{
Instances
A set of vertices and a set of Edges
Operations
NumberOfVertices( ): return the number of vertices in the graph
NumberOfEdges( ): return the number of edges in the graph existsEdge (i, j): return true if
edge (i, j) exists; false otherwise insertEdge(theEdge): insert the edge theEdge into the
graph
eraseEdge(i, j) : delete the edge(i, j)
degree(i ): return the degree of vertex i, defined only for undirected
graphs
inDegree(i): return the in-degree of vertex i
outDegree(i): return the out-degree of vertex i
}
Representation of Graph:
There are two standard ways of maintaining a graph G in the memory of a computer.
1. Sequential representation of a graph using adjacency matrix
2. Linked representation of a graph using linked list
1. Adjacency Matrix Representation
 An adjacency matrix is used to represent which nodes are adjacent to one another.
 The adjacency-matrix representation of an n-vertex graph G = (V, E) is an n x n matrix A.
 Each element of A is either 0 or 1.
 We will assume that vertices set V = {1, 2, . . . , n}.
 if G is an undirected graph, then the elements of A are defined as follows:
 Aij = 1 {if there is an edge from Vi to Vj or Vj to Vi or if the edge (i, j) is member of E.}
 Aij = 0 {if there is no edge from Vi to Vj}
 The adjacency matrix for an undirected graph is symmetric.
 The adjacency matrix A of a directed graph G = (V, E) can be represented with the following
conditions
 Aij = 1 {if there is an edge from Vi to Vj or if the edge (i, j) is member of E.}
 Aij = 0 {if there is no edge from Vi to Vj}
 The adjacency matrix A for a directed weighted graph G = (V, E, We ) can be represented as
 Aij= Wij { if there is an edge from Vi to Vj then represent its weight Wij.}
 Aij= 0 { if there is no edge from Vi to Vj}
 For an undirected graph the degree of any vertex i is its row sum.
 For a directed graph the row sum is its out-degree, and the column sum is its in-degree.
 Since an adjacency matrix contains only 0s and 1s, it is called a bit matrix or a Boolean matrix.
The entries in the matrix depend on the ordering of the nodes in G. therefore, a change in the order
of nodes will result in a different adjacency matrix.

Blog: anilkumarprathipati.wordpress.com Page 7


Graph Algorithms UNIT-3

Example

Disadvantages: In this representation, n2 memory location is required to represent a graph with n


vertices. The adjacency matrix is a simple way to represent a graph, but it has two disadvantages.
1. It takes n2 space to represent a graph with n vertices, even for a sparse graph and
2. When adjacency matrices are used, we need O(n) time to determine the set of vertices adjacent to
or from any given vertex.
3. It takes O(n2 ) time to solve the graph problem
4. But, we can add or delete an edge in O(1) time.
2. Linked List Representation (also called adjacency list representation): In this representation, graph
is created or represented with dynamic data structure that is linked list. The graph can be represented
using linked list where the node structure is defined as
struct node
{ Vertex Label next
char vertex;
struct node*next;
};
 The n rows of the adjacency matrix are represented as n linked lists (or chains).
 There is one list (or chain) for each vertex in G.
 The nodes in list i represent the vertices that are adjacent from vertex i.
 Each node has at least two fields: data and link.
 The data field of a list node stores the index of an adjacent vertex.
 The vertices in each list are not required to be ordered.
 Each list has a head node.
 The head nodes are sequential, providing easy random access to the adjacency list for any
particular vertex.
 For an undirected graph with n vertices and e edges, this representation requires n head nodes
and 2e list nodes.
 The degree of any vertex in an undirected graph may be determined by just counting the number
of nodes in its adjacency list. So, the number of edges in G’ may be determined in O(n + e) time.
 For a digraph, the number of list nodes is only e. The out-degree of any vertex may be determined
by counting the number of nodes on its adjacency list.

Blog: anilkumarprathipati.wordpress.com Page 8


Graph Algorithms UNIT-3

 In the linked-adjacency-list representation of a weighted graph, each node contains two data
fields.
o Vertex and weight
struct node
{ Vertex Label Weight
char vertex;
int weight;
struct node*next;
};
Examples for Graph Representation:

Some – other examples:

(a) An undirected graph (b) An adjacency-list (c) The adjacency-matrix

(a) A directed graph G (b) An adjacency-list (c) The adjacency-matrix

Blog: anilkumarprathipati.wordpress.com Page 9


Graph Algorithms UNIT-3

(a) A weighted directed graph (b) An adjacency-list (c) The adjacency-matrix


3. Incidence Matrix representation: In this representation, if G is a graph with n vertices, e edges and
no self-loops, then incidence matrix A is defined as an n by e matrix, say A = (a i,j), where
ai,j = 1 if there is an edge j incident to vi
ai,j = 0 otherwise
Here, n rows correspond to n vertices and e columns correspond to e edges. Such a matrix is called as
vertex-edge incidence matrix or simply incidence matrix.

4. Adjacency Multi-list Representation: Graphs can also be represented using multi-lists which can be
said to be modified version of adjacency lists.
 Adjacency multi-list is an edge-based rather than a vertex-based representation of graphs.
 A multi-list representation basically consists of two parts—a directory of nodes’ information and a
set of linked lists storing information about edges.
 While there is a single entry for each node in the node directory, every node, on the other hand,
appears in two adjacency lists (one for the node at each end of the edge).
 For example, the directory entry for node i points to the adjacency list for node i. This means that
the nodes are shared among several lists.
 In a multi-list representation, the information about an edge (vi, vj) of an undirected graph can
be stored using the following attributes:
 M: A single bit field to indicate whether the edge has been examined or not.
 vi: A vertex in the graph that is connected to vertex vj by an edge.
 vj: A vertex in the graph that is connected to vertex vi by an edge.
 Link i for vi: A link that points to another node that has an edge incident on v i.
 Link j for vj: A link that points to another node that has an edge incident on v j.
Example – 1: Consider the undirected graph given in below. The adjacency multi-list for the graph can
be given below. Using the adjacency multi-list given above, the adjacency list for vertices can be
constructed as shown below figure.

Blog: anilkumarprathipati.wordpress.com Page 10


Graph Algorithms UNIT-3

Adjacency Matrix vs Adjacency List

Adjacency Matrix Adjacency List


Uses O(n^2) memory. Memory usage depends more on the number of
edges (and less on the number of nodes), which
might save a lot of memory if the adjacency
matrix is sparse.
It is fast to lookup and check for presence or Finding the presence or absence of specific edge
absence of a specific edge between any two between any two nodes is slightly slower than
nodes O(1). with the matrix O(k); where k is the number of
neighbors nodes.
It is slow to iterate over all edges. It is fast to iterate over all edges because you can
access any node neighbors directly.

It is slow to add/delete a node; a complex It is fast to add/delete a node; easier than the
operation O(n^2). matrix representation
It is fast to add a new edge O(1). It fast to add a new
edge O(1).

Blog: anilkumarprathipati.wordpress.com Page 11


Graph Algorithms UNIT-3

4. Operations on graphs
1. Creation of graph
2. Insert vertex
3. Delete vertex
4. Add edge
5. Delete edge
6. Find a vertex
7. Traversal of a graph (visit all the vertices)
1. Creation of a graph: The algorithm for creation of graph using adjacency matrix will be as follows:
1. Declare an array of A[n][n] which will store graph, where n is the number of vertices in G.
2. Enter how many nodes you want in a graph
3. Enter the edges of the graph by two vertices each, say vi, vj indicates some edge.
4. If the graph is directed then set A[i][j] = 1
5. If the graph is undirected then set A[i][j] = A[j][i] = 1
6. When all edges of the desired graph is entered, then print the graph A.
2. Insert Vertex: Insert vertex adds a new vertex to a graph. When the vertex is inserted, it must be
connected.

3. Delete Vertex: Delete vertex removes a vertex from the graph. When a vertex is deleted, all
connecting edges are also removed.

If we delete vertex v4, then the neighboring vertices are v1, v2, v3 set to 0. That is, A[v4][v1] =A[v1][v4]
= 0 ; A[v4][v2] =A[v2][v4] = 0; A[v4][v3] =A[v3][v4] = 0.

Blog: anilkumarprathipati.wordpress.com Page 12


Graph Algorithms UNIT-3

4. Add edge: We can insert an edge in the graph. The edge is always represented by two vertices. So, to
add an edge, two vertices must be specified.
Example:

5. Delete Edge: Delete edge removes one edge from a graph. An edge can be removed by giving its two
vertices V1 and V2.

Example: Before deletion of an edge

Delete edge (v2, v3)

Blog: anilkumarprathipati.wordpress.com Page 13


Graph Algorithms UNIT-3

6. Find vertex: Find vertex traverses a graph, looking for a specified vertex. If the vertex is found, its
data are returned. If it is not found, an error is indicated.
1. Represent the following graph using adjacency matrix, adjacency list and incidence matrix.

5. Graph Traversal techniques


Given a graph G = (V, E) and a vertex v in V(G), we wish to visit all vertices in G that are reachable from
v (i.e., all vertices that are connected to v). There are two standard methods of graph traversal. They are:
i) depth-first search ii) breadth-first search
 Depth First Search (DFS) is similar to a preorder tree traversal.
 Breadth First Search (BFS) is similar to a level order tree traversal.
 These methods work on both directed and undirected graphs.
 We shall assume that the linked adjacency list representation for graphs is used.

i. Depth First Search (DFS): The DFS procedure as shown below:

 Starting at a vertex v, a DFS proceeds as follows:


 First the vertex v is marked as reached, and then an unreached vertex u adjacent from v is selected.
If such a vertex does not exist, the search terminates. Assume that a u as described exists. A DFS
from u is now initiated. When this search is completed, we select another unreached vertex
adjacent from v. if such a vertex does not exist, then the search terminates. If such a vertex exists,
a DFS is initiated from this vertex, and so on.

Algorithm depthFirstSearch (s) /* s is the start vertex */


{
visited(s) = 1;
print (s); /* Output visited vertex */
for each vertex v adjacent to s do
if visited(v) = 0 then call DFT(v);
end
}

Depth First Search function:


void Graph ::DFS( )
{
int visited[n], i; // visited status of N vertices is declared as a Boolean i.e., 0 or 1
for( i = 1; i <= n; i++)
visited [i ] = 0; // initially, no vertices have been visited
dfs (0); // start search at vertex 0
}

Blog: anilkumarprathipati.wordpress.com Page 14


Graph Algorithms UNIT-3

void Graph::dfs ( int v )


// visit all previously unvisited vertices that are reachable from vertex v
{
visited [v] = 1;
for(each vertex w adjacent to v)
{
print ( v );
if( visited [w] != 1)
DFS(w);
}
}
Example – 1:
Consider the following example graph to perform DFS traversal.

Step – 1: Select the vertex A as starting point (visit A)


Push A on to the stack.

Step – 2: Visit any adjacent vertex of A which is not visited (B).


Push newly visited vertex B on to the stack.

Step – 3: Visit any adjacent vertex of B which is not visited (C).


Push C on to the stack.

Step – 4: Visit any adjacent vertex of C which is not visited (E).


Push E on to the stack.

Blog: anilkumarprathipati.wordpress.com Page 15


Graph Algorithms UNIT-3

Step – 5: Visit any adjacent vertex of E which is not visited (D).


Push D on to the stack.

Step – 6: There is no new vertex to be visited from D. So use back track. Pop D
on to the stack.

Step – 7: Visit any adjacent vertex of E which is not visited (F).


Push F on to the stack.

Step – 8: Visit any adjacent vertex of F which is not visited (G).


Push G on to the stack.

Step – 9: There is no new vertex to be visited from G. So use back track. Pop G
on to the stack.

Blog: anilkumarprathipati.wordpress.com Page 16


Graph Algorithms UNIT-3

Step – 10: There is no new vertex to be visited from F. So use back track. Pop F
on to the stack.

Step – 11: There is no new vertex to be visited from E. So use back track. Pop E
on to the stack.

Step – 12: There is no new vertex to be visited from C. So use back track. Pop C
on to the stack.

Step – 13: There is no new vertex to be visited from B. So use back track. Pop B
on to the stack.

Step – 14: There is no new vertex to be visited from A. So use back track. Pop A
on to the stack.

Stack became empty. So, stop DFS traversal. Final result of DFS is
A – B – C – E – D – F – G.
Blog: anilkumarprathipati.wordpress.com Page 17
Graph Algorithms UNIT-3

Example – 2:

Consider the above graph (a), and assume start vertex v = 1.


 If v = 1, then vertices 2, 3, and 4 are adjacent. So, select vertex 2.
 A DFS from vertex 2 is now initiated. Vertex 2 is marked as visited. The only adjacent vertex is 5,
and a DFS from 5 is initiated.
 Vertex 5 is marked as visited, and then a DFS from 8 is initiated.
 Next, vertex 8 is marked as visited. From 8 there are no visited adjacent vertices, so, the algorithm
backs up to vertex 5. There are no new adjacent vertices, so back up to 2, and then to 1.
 Now, for vertex 1 there are two adjacent vertices 3 and 4. Now, vertex 3 is marked as visited.
From 3 there are no visited adjacent vertices, so, the algorithm backs up to vertex 1.
 Next, for vertex 1 the other adjacent vertex is 4. Now, vertex 4 is marked as visited. The adjacent
vertex is 6 and then a DFS from 6 is initiated.
 Next, vertex 6 is marked as visited. From 6 there are no unvisited adjacent vertices, so, the
algorithm backs up to vertex 4.
 Next, for vertex 4 the other adjacent vertex is 7. Now, vertex 7 is marked as visited. The adjacent
vertex is 9 and then a DFS from 9 is initiated.
 Vertex 9 is marked as visited, and there is no adjacent unvisited vertex, so backs up to vertex 4,
and then to 1. There are no other new adjacent vertices so the algorithm stops. Figure (b) shows
the DFS.
 The DFS traversal is 1 – 2 – 5 – 8 – 3 – 4 – 6 – 7.

Example – 3:
Consider the graph G, which is represented by its adjacency lists as shown in Figure. If a depth-first
search is initiated from vertex 0, then the vertices of G are visited in the following order: 0 1 3 7 4 5 2 6.
Since DFS(0) visits all vertices that can be reached from 0 the vertices visited, together with all edges in
G incident to these vertices form a connected component of G.

Blog: anilkumarprathipati.wordpress.com Page 18


Graph Algorithms UNIT-3

The depth first search order: v0, v1, v3, v7, v4, v5, v2, v6.

Analysis or DFS:
 When G is represented by its adjacency lists, the vertices w adjacent to v can be determined by
following a chain of links.
 Since DFS examines each node (v) in the adjacency lists at most once and there are 2e list nodes
the time to complete the search is O(v+e).
 If G is represented by its adjacency matrix then the time to determine all
vertices adjacent to v is O(n). Since at most n vertices are visited the total time is O( n2).

ii. Breadth First Search


In a breadth-first search, we begin by visiting the start vertex v. Next, all unvisited vertices adjacent to v
are visited. Unvisited vertices adjacent to these newly visited vertices are then visited and so on.
Procedure for implementing the BFS:
 Breadth First Search starts at vertex v and marks it as visited.
 Then visiting each of the vertices on v’s adjacency list.
 When we have visited all the vertices on v’s adjacency list, we visit all the unvisited vertices that
are adjacent to the firs vertex on v’s adjacency list.
 To implement this scheme, as we visit each vertex we place the vertex in a queue.
 When we have exhausted an adjacency list, we remove a vertex from the queue and proceed by
examining each of the vertices on its adjacency list.
 Unvisited vertices are visited and placed on the queue; visited are ignored.
 We have finished the search when the queue is empty.

Blog: anilkumarprathipati.wordpress.com Page 19


Graph Algorithms UNIT-3

Algorithm for BFS:


BreadthFirstSearch (v )
{
Label vertex v as reached.
Initialize Q to be a queue with only v in it
While ( Q is not Empty )
{
Delete a vertex w from the queue
Let u be a vertex ( if any ) adjacent from w
while ( u != NULL )
{
if ( u has not been reached )
{
Add u to the queue
Label u as reached
}
u = next vertex that is adjacent from w
}
}
}
Breadth First Search function:
void Graph::BFS(int v)
// A breadth first search of the graph is carried out beginning at vertex v.
// visited [i] is set to TRUE when v is visited. The algorithm uses a queue
{
int visited[n], i; // visited status of N vertices is declared as a Boolean i.e., 0 or 1
for( i = 1; i <= n; i++)
visited [i ] = 0; // initially, no vertices have been visited
visited [v] = 1;
Queue q; // q is a queue
q.insert (v); // add vertex to the queue
while (q.IsEmpty ()==0)
{
v = q.Delete ( ); // remove vertex v from the queue
print ( v );
for (all vertices w adjacent to v)
{
if ( visited [w] != 1)
{
q.insert(w);
visited [w] = 1;
}
}
}
}
Example – 1: Consider the following example graph to perform BFS traversal.

Step – 1: Select the vertex A as starting point (visit A)


Blog: anilkumarprathipati.wordpress.com Page 20
Graph Algorithms UNIT-3

insert A into the Queue.

Step – 2: Visit all adjacent vertices of A which are not visited (B, D, E).
Insert newly visited vertices into the queue and delete A from queue.

Step – 3: Visit all adjacent vertices of D which are not visited (there is no vertex). Delete D from
queue.

Step – 4: Visit all adjacent vertices of E which are not visited (C, F).
Insert newly visited vertices into the queue and delete E from queue.

Step – 5: Visit all adjacent vertices of B which are not visited (there is no vertex). Delete B from
queue..

Step – 6: Visit all adjacent vertices of C which are not visited (G).
Insert newly visited vertices into the queue and delete C from queue.

Step – 7: Visit all adjacent vertices of F which are not visited (there is no vertex). Delete F from
queue.
Blog: anilkumarprathipati.wordpress.com Page 21
Graph Algorithms UNIT-3

Step – 8: Visit all adjacent vertices of G which are not visited (there is no vertex). Delete G from
queue.

Queue became empty. So, stop BFS traversal. Final result of BFS is
A – D – E – B – C – F – G.

Example – 2:

Consider the above graph. Now, take start vertex v as 1.


 Initially, 1 is visited and then vertices 2, 3 and 4 will get added to queue during the first iteration
of outer while loop.
 In the next iteration of this loop, 2 is removed from the queue, and vertex 5 added to it.
 Next 3 is deleted from queue, and no new vertices are added.
 Then 4 is deleted and 6 and 7 are added;
 5 is deleted and 8 added; 6 is deleted and nothing added; and 7 is deleted and 9 added.
 Finally, 8 and 9 are deleted, and the queue becomes empty.

Blog: anilkumarprathipati.wordpress.com Page 22


Graph Algorithms UNIT-3

 The procedure terminates, and the vertices 1 through 9 marked as visited. So, the BFS is 1, 2, 3, 4,
5, 6, 7, 8, 9.
Example – 3: Consider the graph of below Figure. If a breadth-first search is performed beginning at
vertex 0, then we first visit vertex 0. Next, vertices 1 and 2 are visited. Then vertices 3, 4, 5, and 6, and
finally 7, are visited.

The breadth first search order: v0, v1, v2, v3, v4, v5, v6, v7.
Analysis of BFS:
 Each visited vertex enters the queue exactly once.
 So, the while loop is iterated at most n times.
 If an adjacency matrix is used the loop takes O(n) time for each vertex visited. The total time is
therefore, O(n2).
 If adjacency lists are used, the loop has a total cost of deg(0) + deg (1) + … + deg(n) = O(e) where
deg is the degree of vertex i.

BFS vs DFS
BFS (Breadth First Search) DFS (Depth First Search)
It uses Queue data structure for finding the It uses Stack data structure for finding the
shortest path shortest path
In BFS, we can be find single source shortest In DFS, we might traverse through more edges
path in an un-weighted graph, because in to reach a destination vertex from a source.
BFS, we reach a vertex with minimum
number of edges from a source vertex.
It is more suitable for searching vertices It is more suitable when there are solutions
which are closer to the given source. away from source.
Applications: Spanning Trees, Connected Applications: Spanning Trees, Connected
components (paths), Cycles, and shortest components (paths), Cycles, and Bi-connected
Paths. (bipartite) Components.
The Time complexity of BFS and DFS is O(V + E) when Adjacency List is used and O(V^2)
when Adjacency Matrix is used, where V stands for vertices and E stands for edges.

Blog: anilkumarprathipati.wordpress.com Page 23


Graph Algorithms UNIT-3

6. Graph Traversal techniques


The topological sorting problem: given a directed acyclic graph G = (V, E) , find a linear ordering of
the vertices such that for all (v, w) ϵ E, v precedes w in the ordering.
Algorithm:
• Step 1: Create the graph by calling addEdge(a,b).
• Step 2: Call the topologicalSort( )
• Step 2.1: Create a stack and a boolean array named as visited[ ];
• Step 2.2: Mark all the vertices as not visited i.e. initialize visited[ ] with 'false' value.
• Step 2.3: Call the recursive helper function topologicalSortUtil() to store Topological Sort
starting from all vertices one by one.
• Step 3: def topologicalSortUtil(int v, bool visited[],stack<int> &Stack):
• Step 3.1: Mark the current node as visited.
• Step 3.2: Recur for all the vertices adjacent to this vertex.
• Step 3.3: Push current vertex to stack which stores result.
• Step 4: Atlast after return from the utility function, print contents of stack.

Blog: anilkumarprathipati.wordpress.com Page 24


Graph Algorithms UNIT-3

Blog: anilkumarprathipati.wordpress.com Page 25


Graph Algorithms UNIT-3

Time bound: Now the time for each part is


Find vertices with no predecessors: O(|V|)
Remove edges: O(|E|)
Place vertices in output: O(|V|)
Total: O(|V|+|E|)

7. GREEDY - General Method


Greedy method: It is most straight forward method. It is popular for obtaining the optimized
solutions.
Optimization Problem: An optimization problem is the problem of finding the best solution
(optimal solution) from all the feasible solutions (practicable of possible solutions). In an optimization
problem we are given a set of constraints and an optimization functions. Solutions that satisfy the
constraints are called feasible solutions. A feasible solution for which the optimization function has the
best possible value is called optimal solution.
Ex:Problem:Finding a minimum spanning tree from a weighted connected undirected graph G.
Constraints: Every time a minimum edge is added to the tree and adding of an edge does not
form a simple circuit.
Feasible solutions:The feasible solutions are the spanning trees of the given graph G.
Optimal solution: An optimal solution is a spanning tree with minimum cost i.e. minimum
spanning tree.
Q: Find the minimum spanning tree for the following graph.
2
A B

3 1

C D
2
Graph G
Fig: Graph
The feasible solutions are the spanning tree of the graph G. Those are
2 2 2
A B A B A B A B

3 1 3 1 3 1

C D C D C D C D
2 2 2
1 .Total Weights=6 2 .Total Weights=6 3 .Total Weights=7 4 .Total Weights=5
Fig: Spanning trees for the above graph
From the above spanning tree the figure 4 gives the optimal solution, because it is the spanning
tree with the minimum cost i.e. it is a minimum spanning tree of the graph G.
The greedy technique suggests constructing a solution to an optimization problem through a
sequence of steps, each expanding a partially constructed solution obtained so far until a complete
solution to the problem is reached to each step, the choice made must be feasible, locally optimal and
irrecoverable.
Feasible: The choice which is made has to be satisfying the problems constraints.
Locally optimal: The choice has to be the best local choice among all feasible choices available on
that step.
Irrecoverable: The choice once made cannot be changed on sub-sequent steps of the algorithm
(Greedy method).

Blog: anilkumarprathipati.wordpress.com Page 26


Graph Algorithms UNIT-3

Control Abstraction for Greedy Method:


Algorithm GreedyMethod (a, n)
{
// a is an array of n inputs
Solution: =Ø;
for i: =0 to n do
{
s: = select (a);
if (feasible (Solution, s)) then
{
Solution: = union (Solution, s);
}
else
reject (); // if solution is not feasible reject it.
}
return solution;
}
In greedy method there are three important activities.
1. A selection of solution from the given input domain is performed, i.e. s:= select(a).
2. The feasibility of the solution is performed, by using feasible ‘(solution, s)’ and then all feasible
solutions are obtained.
3. From the set of feasible solutions, the particular solution that minimizes or maximizes the given
objection function is obtained. Such a solution is called optimal solution.
Greedy designing technique is not possible to apply the entire real world optimization problems.
Example: Coin change problem.
Greedy solution as:
1. Let's start by having the values of the coins in an array in reverse sorted order.
2. Now if we have to make a value of n using these coins, then we will check for the first element in
the array (greedy choice) and if it is greater than n, we will move to the next element, otherwise
take it. Now after taking one coin with value coins[i], the total value which we have to make will
become n-coins[i].
3. If total value becomes zero, stop it. Otherwise repeat the step 2.
Q1: A child buys a candy 42 rupees and gives a 100 note to the cashier. Then the cashier wishes to return
change using the fewest number of coins. Assume that the cashier has Rs.1, Rs. 5 and Rs. 10 coins.
Is this problem can be solved using the greedy method? Yes. (5*10 + 1*5 + 3*1 = 9 coins are the
minimum number)
Q2: A child buys a candy 89 rupees and gives a 100 note to the cashier. Then the cashier wishes to return
change using the fewest number of coins. Assume that the cashier has Rs.1, Rs. 5, Rs. 6 and Rs. 9 coins.
Is this problem can be solved using the greedy method? No. (1*9 + 1*2 = 2 coins, but optimally
1*6 + 1*5 = totally 2 coins are the minimum number.)

8. Applications – Minimum Spanning Tree

A spanning tree is a subset of Graph G, which has all the vertices covered with minimum possible
number of edges. Hence, a spanning tree does not have cycles and it cannot be disconnected.
Note: Every connected and undirected Graph G has at least one spanning tree. A disconnected
graph does not have any spanning tree.

Blog: anilkumarprathipati.wordpress.com Page 27


Graph Algorithms UNIT-3

Fig: Example of Graph and its possible spanning trees


We found three spanning trees off one complete graph. A complete undirected graph can have
maximum nn-2 number of spanning trees, where n is the number of nodes. In the above addressed
example, 33−2 = 3 spanning trees are possible.
General Properties of Spanning Tree
 A connected graph G can have more than one spanning tree.
 All possible spanning trees of graph G, have the same number of edges and vertices.
 The spanning tree does not have any cycle (loops).
 Removing one edge from the spanning tree will make the graph disconnected, i.e. the
spanning tree is minimally connected.
 Adding one edge to the spanning tree will create a circuit or loop, i.e. the spanning tree
is maximally acyclic.
Mathematical Properties of Spanning Tree
 Spanning tree has n-1 edges, where n is the number of nodes (vertices).
 From a complete graph, by removing maximum e - n + 1 edges, we can construct a
spanning tree.
 A complete graph can have maximum nn-2 number of spanning trees.
Thus, we can conclude that spanning trees are a subset of connected Graph G and disconnected
graphs do not have spanning tree.
Application of Spanning Tree
Spanning tree is basically used to find a minimum path to connect all nodes in a graph. Common
applications of spanning trees are
 Civil Network Planning
 Computer Network Routing Protocol
 Cluster Analysis
Let us understand this through a small example. Consider, city network as a huge graph and now
plans to deploy telephone lines in such a way that in minimum lines we can connect to all city nodes. This
is where the spanning tree comes into picture.
Minimum Spanning Tree (MST)
In a weighted graph, a minimum spanning tree is a spanning tree that has minimum weight than
all other spanning trees of the same graph. In real-world situations, this weight an be measured as
distance, congestion, traffic load or any arbitrary value denoted to the edges.
Minimum Spanning-Tree Algorithm
We shall learn about two most important spanning tree algorithms(greedy algorithms):
1. Kruskal's Algorithm
2. Prim's Algorithm

Blog: anilkumarprathipati.wordpress.com Page 28


Graph Algorithms UNIT-3

i. Kruskal's Algorithm
It is used to find the minimum cost spanning tree uses the greedy approach. This algorithm treats
the graph as a forest and every node it has as an individual tree. A tree connects to another only and only
if, it has the least cost among all available options and does not violate MST properties.
To understand Kruskal's algorithm let us consider the following example:

Fig: Example of Graph to find MST

Step 1 - Remove all loops and Parallel Edges


Remove all loops and parallel edges from the given graph.

Fig: Identifying self loops, and multi edges

In case of parallel edges, keep the one which has the least cost associated and remove all others. Only
thick line represents the edge between vertices/nodes.

Fig: Graph after removing self loops, and multi edges

Step 2 - Arrange all edges in their increasing order of weight


The next step is to create a set of edges and weight, and arrange them in an ascending order of weight
(cost).

Fig: Edges are sorted in increasing order

Blog: anilkumarprathipati.wordpress.com Page 29


Graph Algorithms UNIT-3

Step 3 - Add the edge which has the least weightage


Now we start adding edges to the graph beginning from the one which has the least weight. Throughout,
we shall keep checking that the spanning properties remain intact. In case, by adding one edge, the
spanning tree property does not hold then we shall consider not to include the edge in the graph.

Fig: min cost (2) edge(s) is added in MST

The least cost is 2 and edges involved are B,D and D,T. We add them. Adding them does not
violate spanning tree properties, so we continue to our next edge selection.
Next cost is 3, and associated edges are A,C and C,D. We add them again −

Fig: min cost (3) edge(s) is added in MST

Next cost in the table is 4, and we observe that adding it will create a circuit in the graph. −

Fig: min cost (4) edge(s) is not added in MST

We ignore it. In the process we shall ignore/avoid all edges that create a circuit.

Fig: min cost (5 and 6) edge(s) is not added in MST

We observe that edges with cost 5 and 6 also create circuits. We ignore them and move on.
Now we are left with only one node to be added. Between the two least cost edges available 7 and 8, we
shall add the edge with cost 7.

Blog: anilkumarprathipati.wordpress.com Page 30


Graph Algorithms UNIT-3

Fig: min cost (7) edge(s) is added in MST

By adding edge S,A we have included all the nodes of the graph and we now have minimum cost
spanning tree.
Example -2: Consider the below graph to find the MST

Fig: one more example of MST

Fig - 16: step wise construction of MST


Kruskal’s Algorithm:

Blog: anilkumarprathipati.wordpress.com Page 31


Graph Algorithms UNIT-3

Time Complexity = O (|E| log |E|)

Fig: one more example of MST

Example Initially each vertex is in a different set {1}{2}{3}{4}{5}{6}.


Consider (1, 2):
J=1, 1= Find(1); k = 2 = Find(2), 1 ≠2 so i=1
(1,2) is included and union (1,2) = {1,2}
Consider (3,6):
Test if (3,6) is forming a cycle with (1,2), 3= Find (3), 6 = Find (6), 3 ≠ 6 so i=2, then (3,6) is
included;
UNION (3,6) = (3,6).
Consider (4,6):
4= Find(4) ; Find(6) is 3, 3≠ 4 so i= 3 and (4, 6) is added and union (3, 4) = (3, 4, 6) Consider
(2,6). Find (2) =1, Find (6) =3, now union (1,3) is union {1,2,3,4,6}.
Consider (1, 4):
1= Find (1), 1= Find (4), The root of the tree in which 1 and 4 belong is the same; it means 1 and
4 form a cycle, and hence (1, 4) is rejected.
Consider (3, 5):
1= Find (3), 5= Find (5), 3 and 5 belong to different sets hence edge (3,5) is included. The total
cost of the spanning tree is 105.
The Minimums cost spanning tree as:

Blog: anilkumarprathipati.wordpress.com Page 32


Graph Algorithms UNIT-3

Fig: MST for the above graph.


Time Complexity: The edges are maintained as a min heap. The next edge can be obtained / deleted in O
(log e) time if G has e edges. Reconstruction of heap using ADJUST takes O (e) time. Therefore,
Kruskal’s algorithm takes O (e loge) time.
ii. Prim’s Algorithm
Prim's algorithm to find minimum cost spanning tree (as Kruskal's algorithm) uses the greedy
approach. Prim's algorithm shares a similarity with the shortest path first algorithms.
Prim's algorithm, in contrast with Kruskal's algorithm, treats the nodes as a single tree and keeps
on adding new nodes to the spanning tree from the given graph. To contrast with Kruskal's algorithm and
to understand Prim's algorithm better, we shall use the same example.

Fig: Example of Graph to find MST

Step 1 - Remove all loops and parallel edges

Fig: Identifying self loops, and multi edges

Remove all loops and parallel edges from the given graph. In case of parallel edges, keep the one
which has the least cost associated and remove all others.

Fig: Graph after removing self loops, and multi edges


Step 2 - Choose any arbitrary node as root node
In this case, we choose S node as the root node of Prim's spanning tree. This node is arbitrarily
chosen, so any node can be the root node. One may wonder why any video can be a root node. So the
answer is, in the spanning tree all the nodes of a graph are included and because it is connected then there
must be at least one edge, which will join it to the rest of the tree.
Blog: anilkumarprathipati.wordpress.com Page 33
Graph Algorithms UNIT-3

Step 3 - Check outgoing edges and select the one with less cost
After choosing the root node S, we see that S,A and S,C are two edges with weight 7 and 8,
respectively. We choose the edge S,A as it is lesser than the other.

Fig: Identifying starting vertex as S

Now, the tree S-7-A is treated as one node and we check for all edges going out from it. We
select the one which has the lowest cost and include it in the tree.

Fig: Edge S to A is added in MST

After this step, S-7-A-3-C tree is formed. Now we'll again treat it as a node and will check all the
edges again. However, we will choose only the least cost edge. In this case, C-3-D is the new edge,
which is less than other edges' cost 8, 6, 4, etc.

Fig: Edges A to C and C to D are added in MST


After adding node D to the spanning tree, we now have two edges going out of it having the same
cost, i.e. D-2-T and D-2-B. Thus, we can add either one. But the next step will again yield edge 2 as the
least cost. Hence, we are showing a spanning tree with both edges included.

Fig: Edges D to B and D to T are added in MST

We may find that the output spanning tree of the same graph using two different algorithms is
same.

Blog: anilkumarprathipati.wordpress.com Page 34


Graph Algorithms UNIT-3

Fig: step wise construction of MST


Prim’s Algorithm:

Time Complexity = O (|V|2)

Blog: anilkumarprathipati.wordpress.com Page 35


Graph Algorithms UNIT-3

Fig: one more example of MST

Explanation of Prim’s algorithm:


Near(k) =0 means zero is a fictious vertex such that cost (k,0) is always minimum; it means you
need not find any vertex near to k or l or near to any other vertex already included in the spanning tree.
Near (k) ≠ 0 means consider vertices which are not included in the spanning tree. After including a
minimum cost edge near (i) is computed for each i= 1,…n. Near (i) is the vertex (out of the two vertices
in the included edge) which is near to i. Near (i) is computed so that after including an edge, we need to
find the vertex with which we are trying to form the new /next edge in the spanning tree.
To exclude already included edges, make near (k) is 0, near (l) is 0 if (k, L) is included. In the
second for-loop we are finding i which forms an edge with near (i) and having minimum cost. Updating
near values is required because near(i) returns a vertex (already in the spanning tree being formed) with
which edge is existing and to be included and it may change dynamically due to inclusion of new edge
and hence new vertex.
For example near(3) is 2 and cost(3,2) is 50 when (2,6) is included, near(3) may be 1 or 2 or 6 As
cost(3,6) < cost(3,2) (15 <50) near(3) is 6 (changed from 2 to 6). Minimum cost edge (1, 2) with cost 10
is included Near (3) is 2, Near (4) is 1, Near (5) is 2, Near (6) is 2, Near (1) is 0, Near (2) is 0. Select out
of 3,4,5,6 a vertex such that {Cost (3, 2) = 50 Cost (4, 1) = 30 Cost (5, 2) = 40}
Cost (6, 2) = 25} is minimum, clearly it is 6, therefore j is 6 so the edge j, near (j) i.e. (6, 2) is
included. Now let us update near (k) values k =1…6, Near (1) = near (2) = near (6) = 0, k=3, cost (3, near
(3) = 2) = 50 > cost (3, 6) =15. Therefore near (3) are 6. Near (4) is 6 cost (4, 1) = 30 > cost (4,6) = 20.
Near (5) is 2, and cost (5,2) = 40 < cost (5,6) = 55. Therefore the total cost of the spanning tree is 105.

9. APPLICATION - SINGLE SOURCE SHORTEST PATH PROBLEM


For a given source node in the graph, the algorithm finds the shortest path between that node and
every other. It also used for finding the shortest paths from a single node to a single destination node by
stopping the algorithm once the shortest path to the destination node has been determined.
Vertices in a graph may represent cities and edges may represent sections of highway. The
weights of edges may be distance between two cities or the average time to drive from one city to the other.
The shortest path problem is as below:
Given a directed graph = (V, E) a weighted function c(e) for edges e of G and a source vertex V0.
The problem is to determine the shortest path from vo to all the remaining vertices of G. All
weights are supposed to be positive.

Example:

Blog: anilkumarprathipati.wordpress.com Page 36


Graph Algorithms UNIT-3

Fig: Example of single source shortest path

Algorithm:

Time Complexity = O (n2)

Explanation of above algorithm:

Initially, S(1) = 0; S(2) = 0; …, S(5) = 0. Dist(1) is cost (V0 ,V1) = 50. Dist(2) is cost of (V0,V2)
that is 10. Dist(3) is cost (V0,V3) is α (that means there is no path). Dist(4) is 45. Dist(5) is α. Let S(V0)
is 1 Dist (V0) is 0; For num is 2 to 4 do Dist(2) = min{Dist(1)…Dist(5)} = 10.
Some of Dist(3), … Dist(5) may change. New Dist(3) = min (old Dist(3) = α, Dist(2)+cost(2,3)) =
min(α,10+15) = 25.
New Dist(4) is min (old Dist(4) = 45, Dist(2)+cost(2,4) is min(45,10+α) = 45 new Dist(5) is min
(old Dist(5) = α, Dist(2)+cost(2,5)) = min(α,10+ α) = α. Now choose u such that dist (u)= min{Dist (3),
Dist (4), Dist (5)))} i.e min { 25, 45, α } = 25, Therefore U is 3 S(3) is 1. The process is continued. The
time taken by the algorithm is 0(n2 ).where n is the number of vertices.
The edges on the shortest paths from a vertex v to all remaining vertices in a connected undirected
graph G form a spanning tree of G called shortest path spanning tree. • Shortest path spanning tree for the
above graph.

Blog: anilkumarprathipati.wordpress.com Page 37


Graph Algorithms UNIT-3

Fig: One more example for Single source shortest paths

10. All pairs shortest path problem:


All pairs shortest path problem:-All-pairs shortest-paths problem is to find a shortest path from u to v
for every pair of vertices u and v. Although this problem can be solved by running a single-source
algorithm once from each vertex, it can usually be solved faster using the dynamic programming
technique.
Solving All pairs shortest path problem by dynamic programming
Step 1: -Optimal substructure of a shortest path
Shortest-paths algorithms typically rely on the property that a shortest path between two vertices contains
other shortest paths within it.
Step 2:- A recursive solution

Where C[i,j] is the cost matrix of the given graph.


Step 3:- Computing the distance matrices Dk where k= 1, 2, ….., n.
Step 4:- Finally Dn matrix gives the shortest distance from every vertex I to every other vertex j.
Example:- Find the shortest path between all pair of nodes in the following graph.

Solution:-The cost matrix of the given graph is as follows

C[i, j] =

Blog: anilkumarprathipati.wordpress.com Page 38


Graph Algorithms UNIT-3

We know D0[i,j] = C[i,j] =

Now we have to calculate D1[i,j]


D1[1,1] = min { D0[1,1], D0[1,1]+ D0[1,1]} = min{0, 0+0} = 0
D1[1,2] = min { D0[1,2], D0[1,1]+ D0[1,2]} = min{4, 0+4} = 4
D1[1,3] = min { D0[1,3], D0[1,1]+ D0[1,3]} = min{11, 0+11} = 11
D1[2,1] = min { D0[2,1], D0[2,1]+ D0[1,1]} = min{6, 6+0} = 6
D1[2,2] = min { D0[2,2], D0[2,1]+ D0[1,2]} = min{0, 6+4} = 0
D1[2,3] = min { D0[2,3], D0[2,1]+ D0[1,3]} = min{2, 6+11} = 2
D1[3,1] = min { D0[3,1], D0[3,1]+ D0[1,1]} = min{3, 3+0} = 3
D1[3,2] = min { D0[3,2], D0[3,1]+ D0[1,2]} = min{ , 3+4} = 7
D1[3,3] = min { D0[3,3], D0[3,1]+ D0[1,3]} = min{0, 3+11} = 0
Thus

D1[i,j] =

Similarly using the same procedure we get

D2[i,j] = andD3[i,j] =

As no of nodes in the given graph are 3, So D3 [i,j] gives the shortest distance from every vertex i to every
other vertex j.
Algorithm AllPaths (cost, D, n)
{
for i = 1 to n do
for j = 1 to n do
D[i, j] = cost[i, j];
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] };
}

Time Complexity:-The time needed by All Paths algorithm is especially easy to determine because the
loop is independent of the data in the matrix D. The D[i, j] is obtained after the statement is iterated n 3
times. So the time complexity of All Paths algorithm is Ө(n3).

Blog: anilkumarprathipati.wordpress.com Page 39


Graph Algorithms UNIT-3

GREEDY APPROACH DIVIDE AND CONQUER

1.Many decisions and sequences areguaranteed 1.Divide the given problem into many subproblems.
and all the overlapping subinstancesare consid Find the individual solutions andcombine them to get
ered. the solution for themain problem

2. Follows Bottom-up technique 2. Follows top-down technique

3.Split the input at every possible points rather 3.Split the input only at specific points (midpoint),
each problem is independent.
than at a particular point

4. Subproblems are dependent on the main 4. Subproblems are independent on the main

Problem Problem

5. Time taken by this approach is not that 5. Time taken by this approach efficient when
much efficient when compared with DAC. compared with GA.

6.Space requirement is less when compared 6.Space requirement is very much high when
DAC approach. compared GA approach.

Blog: anilkumarprathipati.wordpress.com Page 40

You might also like