Professional Documents
Culture Documents
INTRODUCTION
We have studied one non-linear data structure so far i.e Trees. A graph is another nonlinear data structure that is widely used to solve many real-life computing problems. For
example, we need to use a graph to find out whether two places on a road-map are
connected and what is the shortest distance between them. Graphs are used in simulating
electrical circuits to find out current flows and voltage drops at various points in the circuit.
Graphs are widely used in telephone and computer networks.
Graphs have great historical significance too. In 1736, the famous mathematician Euler
used the concept of a graph to solve the Koenigsberg problem. In the small town of
Koenisberg in Prussia, the river Pregal flows around the island of Kneiphof and then
divides into two. The four land areas ( A, B, C, D) bordering the river are connected by
seven bridges ( a,b,c,d,e,f,g). The problem is to find out whether it is possible to start
walking from some area, cross each bridge exactly once and return to the starting land
area. Euler used graphs to prove that this would not be possible. A walk which achieves this
is called an Eulerian Walk.
10 - 2
Graphs
V
V
V
G
G
V
G 1= ( V ,E )
V = { V 1, V 2 V 3, V 4}
E = { ( V 1, V 2) , ( V 2, V 3) }
( V 3 , V 4) , ( V 4, V 1) }
V
7
Undirected Graph
A graph is an undirected graph if the pairs of vertices that make up the edges are
unordered pairs.
i.e. an edge(Vi, Vj ) is the same as (Vj, Vi). The graph G1 shown above is an undirected
graph.
Directed Graph
In a directed graph, each edge is represented by a pair of ordered vertices i.e. an edge
has a specific direction.
In such a case, edge (Vi, Vj) (Vj, Vi)
Example
V
V
Directed graph
G5
= (V,E)
10 - 3
Graphs
For an edge (Vi, Vj) in a directed graph, vertex Vi is called the tail and V j is the head of
the edge. Vi is adjacent to Vj and Vj is adjacent from Vi.
Complete Graph
If an undirected graph has n vertices, the maximum number of edges it can have is
nC2 = n (n-1) / 2. If an undirected graph G has n vertices and nC2 edges, it is called a
complete graph.
If the graph G is directed and has n vertices, G is complete if it has n(n-1) edges.
Multigraph
A multigraph is a graph in which the set of edges may have multiple occurrences of the
same edge. Note that it is not a graph.
Degree of Vertex
The degree of a vertex in an undirected graph is the number of edges incident to that
vertex.
In the undirected graph G1, the degree of each vertex = 2.
Indegree of a Vertex
If G is a directed graph, the indegree of a vertex is the number of edges for which it is
head i.e. the numbers edges coming to it.
Example In graph G5, indegree
(V4)
= 2
indegree
(V1)
= 0
Outdegree of a vertex
If G is directed graph, the out degree of a vertex is the number of edges for which it is
the tail i.e. the number of edges going out of it.
Example
outdegree (V1) = 3
outdegree (V2) = 1
10 - 4
Graphs
Adjacent vertices
If (Vi, Vj) is an edge in G, then we say that V i and Vj are adjacent and the edge (V i, Vj) is
incident on Vi and Vj.
Path
A path from vertex Vp to Vq exists if there exists vertices Vi 1, Vi2, ..Vin such that there
exist edges (Vp, Vi1) , (Vi1, Vi2),(Vin, Vq)
Length of a Path
The length of a path is the number of edges on it.
Linear Path
A linear path is a path whose first and last vertices are distinct.
Cycle
A cycle is a path whose first and last vertices are the same.
Example V1 V2 V3 V1 is a cycle in G4. A graph with no cycles is called an acyclic
graph. A directed acyclic graph is called dag.
Connected Graph
Two vertices Vi and Vj are said to be connected if there is a path in G from Vi to Vj.
Strongly Connected Graph: A directed graph G is said to be strongly connected if for
every pair of distinct vertices V i, Vj, there is a directed path from V i to Vj and also from
Vj to Vi.
Weakly Connected Graph : A directed graph G is said to be weakly connected there
exists atleast one set of distinct vertices V i, Vj, such that there is a directed path from V i to
Vj but no path from Vj to Vi.
Example: The following is a weakly connected graph because there is a path from V 1 to V4
but none from V4 to V1.
V
V
10 - 5
Graphs
Subgraph
A subgraph of G is a graph G such that V(G) V(G) and E(G) E(G)
Example: The subgraphs of G1 are
V
V
Subgraphs of G1
Forest
A Forest is defined as an acyclic graph in which every node has one or no predecessors.
10
V
5
V
6
Weighted Graph
Spanning Tree
When a graph G is connected, a traversal method visits all its vertices. In this case the
edges of G are partitioned into two sets.
T for the edges traversed.
B (Back edges) which were not traversed.
The edges in T form a tree which connects all vertices of graph G. Such a tree is called a
spanning tree.
A spanning tree consists of the minimum number of edges to connect all the vertices.
Example
10 - 6
Graphs
g ra p h
( i)
( ii)
( iii)
S p a n n in g tr e e s
A graph and its spanning trees
Spanning Forest
A spanning forest of a graph G = ( V, E) is a collection of vertex disjoint trees Ti = (V i, Ei),
1 i k such that V = Vi for all 1 i k and Ei E(G), 1 i k
GRAPH REPRESENTATION
To represent a graph in memory, we will have to store data in such a way that the
information about vertices and edges can be correctly stored and it is possible to extract the
required information and manipulate it. Hence, it is important to select the correct method
of implementation so that algorithms may be applied on the graph.
Several representations for graphs are possible. However, we shall be studying only
three of them.
i.
Adjacency matrix
ii.
Adjacency list
iii.
Adjacency multilist
The choice of a particular representation will depend upon the application.
10 - 7
Graphs
Adjacency Matrix
g ra p h G
G ra p h G
Adjacency Matrix
The adjacency matrix for an undirected graph will be a symmetric matrix. To find out
whether vertex j is adjacent to vertex i, the matrix element A[i][j] will have to be checked. If
it is 0, it indicates that j is not adjacent to i.
Class definition
The class definition for a graph represented as an adjacency matrix will be :
classgraph
{
intA[10][10];//adjacencymatrix
intno_of_vertices;
public:
//memberfunctions
}
10 - 8
Graphs
Calculation of Degree
i.
Undirected graph
From the adjacency matrix, it is very easy to calculate the degree of vertices of an
undirected graph.
The degree of vertex i is the number of 1s in its row (or the sum of row i )
ii.
Directed graph
(Indegree) For a directed graph, the indegree of vertex i is the sum of elements in
column i, i.e.total number of 1s in column i.
(Outdegree) The outdegree of a vertex i is the sum of row i (i.e. number of 1s in row
i)
Adjacency List
The above method of representation has one major drawback. It uses arrays and hence is
memory inefficient.
Adjacency list is a linked representation of a graph. In this representation, there is one
list for each vertex v in the graph. Each list stores the vertices which are adjacent to vertex
v. Thus, for a graph with n vertices, there are n lists.
Each node of the list i contains two fields - Vertex and Link:
i. Vertex - Vertex number which is adjacent to vertex i.
ii. Link - Pointer to the next node in the list.
Each list has a head node. The array of all head-nodes represents the graph.
Example:
The adjacency list for graph G6 will be
NULL
NULL
NULL
NULL
NULL
10 - 9
Graphs
NULL
NU LL
NULL
N ULL
NULL
Adjacency list for G7
Node Structure
The structure definition will be
classgraphnode
{
intvertex;
graphnode*next;
};
The graph will now be defined as an array of pointers, each pointing to a list of nodes.
classlistgraph
{
graphnode*list[MAX];//arrayofpointers
intn;//numberofvertices
public:
//operations
};
The following program implements a graph using an adjacency list. We will have to
create the list for each vertex by accepting adjacency information from the user. Starting
with vertex 1, we will build the adjacency list till the lists for all the vertices have been
created. Each list will be created in the same manner as we created a singly linked list i.e
by creating nodes and attaching them to the end of the list.
10 - 10
Graphs
{
intvertex;
graphnode*next;
public:
graphnode(intn=0)//constructor
{
vertex=n;
next=NULL;
}
friendclassgraph;
};
classlistgraph
{
graphnode*list[MAX];//arrayofpointers
intn;//numberofvertices
public:
listgraph(intnov)//constructor
{
n=nov;
for(intj=0; j<n;j++)
list[j]=NULL;
}
voidcreate();
voiddisplay();
};
voidlistgraph::create()
{
inti,j;
graphnode*temp,*newnode;
charans;
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
cout<<\nIsthereanedgebetweenvertex<<i+1<<and<<j+1;
cin>>ans;
if(ans==y)
{
newnode=newgraphnode(j+1);//callconstructor
10 - 11
Graphs
/***Attachnewnodetolisti****/
if(list[i]==NULL)
list[i]=temp=newnode;
else
temp>next=newnode;
temp=newnode;
}/*endif*/
}/*endfor*/
}/*endfor*/
}
voidlistgraph::display()
{
graphnode*temp;
inti;
for(i=0;i<n;i++)
{
cout<<endl;
cout<<"Vertex"<<i+1<<>;
temp=list[i];
while(temp!=NULL)/**Traverselisti**/
cout<<"v<<temp>vertex<<>;
temp=temp>next;
cout<<"NULL";
}
}
intmain()
{
intn;
cout<<Enterthenumberofvertices:";
cin>>n;
listgraphg(n);
g.create();
g.display();
return0;
}
Inverse Adjacency List
From the adjacency list we can calculate the outdegree of any vertex i. The total number
of nodes in list i is its outdegree.
10 - 12
Graphs
To obtain the indegree, we can construct an inverse adjacency list. The inverse adjacency
list of G7 is as shown.
N U LL
NULL
NULL
NULL
NULL
Orthogonal List
Vj
Link of Vi
Link of Vj
The link of Vi points to the node where Vi is the tail and link of V j points to the node
where Vj is the head.
Example
3
1
2
H ead
1
T a il
1
2
3
Orthogonal List
Adjacency Multilist
10 - 13
Graphs
Vi
Vj
Path i
Path j
The flag is used to indicate whether edge (Vi, Vj) has been considered or not.
Pathi is the pointer to the next edge where vertex Vi appears.
Pathj is the pointer to the next edge where Vj appears.
Example
V
e1
V
e
2
e5
e2
3
e6
V
e1
e3
e1
e5
e2
e4
e6
e3
e5
e6
V
V
vi vj
pi p
e4
e3
e6
e4
e6
e5
e5
e1
2
e6
Adjacency Multilist
There are 6 edges, e1 to e6 which are <1,2> , <1,3>, <1,4>, <2,3>, <2,4> and <3,4>. The
edges are shown with Vi representing the head and Vj the tail. Pi represents the next edge
where Vi is present and Pj represents the next edge where Vj is present. For example, in
the node for e1 , Pi is e2 where vertex 1 next appears and Pj is e 4 where vertex 2 next
appears
10 - 14
Graphs
To find the adjacency list for any vertex, we start traversal from the node of that vertex.
For example, if we wanted the list corresponding to vertex 1, we have to start from node V1.
From that node, it proceeds as follows:
Node V1 points to e1. In e1, the edge is (1,2). Vertex 1 is Vi. Hence , we select Pi i.e, e 2.
In e2 i.e. (1,3) we take the path to e3.
In e3 i.e. (1,4) we select the path Pi i.e NULL
V1 : e1 e2 e3 NULL
For vertex V2, we begin from edge, e1. Since 2 is Vj, we select path Pj i.e e4.
In e4, 2 is Vi. Hence we take path e5.
In e5 ,2 is Vi. Hence we reach NULL
V2 : e1 e4 e5 NULL
Similarly we get,
V3 : e2 e4 e6 NULL
V4 : e3 e5 e6 NULL
GRAPH TRAVERSALS
Traversal is the method to reach every vertex of a graph. Graph traversals are more
complicated as compared to tree traversals because a single vertex may be visited many
times and the traversal may not terminate.
Hence, we also need a method of identifying a vertex, which has been visited previously
so that we dont keep traversing from the same vertex again and again. This can be done
by using a flag ( a variable) which will store 0 if the vertex is not visited and 1 if visited.
Two methods are used for graph traversal
Starting from a particular vertex v which is unvisited, we visit its unvisited adjacent
vertex, mark it visited and continue in the same way from this vertex till we reach a vertex
which does not have any unvisited neighbor. That is, starting from vertex v, we follow a
10 - 15
Graphs
path in the graph as deeply as we can go marking the vertices in the path as visited.
When there are no adjacent vertices that are not visited, we proceed backwards (back track)
to a vertex in the path which has an unvisited adjacent vertex and proceed from this
vertex. The process continues till all vertices have been visited.
The process terminates when no unvisited vertex can be reached from any of the visited
vertices.
Example
V
V
V
i.
i.
Recursive
ii.
Non recursive
We start with vertex v and mark it visited. A vertex w, which is adjacent to v and not
visited, is selected. A recursive call is given to the Depth First Search from w. The process
stops when all vertices are visited.
We require a global array visited of size n , which is initialized to zero.
AlgorithmrecDFS(intv)
//visitedisaglobalarrayinitializedtozero
//visthestartingvertex
{
visited[v]=1;/*Markvvisited*/
10 - 16
Graphs
displayv
foreachvertexwadjacenttovdo
if(wisnotvisited)then
recDFS(w);//recursivecall
}
ii.
1.
2.
3.
Visited [v] = 1
4.
display v.
5.
6.
7.
if w is found
visited[w] = 1
display w
push w into stack
v = w i.e. w becomes the current vertex.
Go to step 6
8.
v = pop
9.
10.
Stop
For example, consider the graph in Fig 10.12 above. Here, we start from vertex V 1. The
steps are shown below.
10 - 17
Graphs
V1
Visited
Stack
V1
V1
V1
V2
V1 V2
V1 V2
V2
V4
V1V2 V4
V1V2 V4
V4
V8
V1V2 V4 V8
V1V2 V4 V8
V8
V5
V1V2 V4 V8 V5
V1V2 V4 V8 V5
V5
Not found
V1V2 V4 V8 V5
V1V2 V4
Pop
V8
V6
V1V2 V4 V8 V5 V6
V1V2 V4 V6
Pop
V6
V3
V1V2 V4 V8 V5 V6 V3
V1V2 V4 V6 V3
V3
V7
V1V2 V4 V8 V5 V6 V3 V7
V1V2 V4 V6 V3 V7
V7
Not found
V1V2 V4 V8 V5 V6 V3 V7
V1V2 V4 V6 V3
Pop
V7
Not found
V1V2 V4 V8 V5 V6 V3 V7
V1V2 V4 V6
Pop
V3
Not found
V1V2 V4 V8 V5 V6 V3 V7
V1V2 V4
Pop
V6
Not found
V1V2 V4 V8 V5 V6 V3 V7
V1V2
Pop
V4
Not found
V1V2 V4 V8 V5 V6 V3 V7
V1
Pop
V2
Not found
V1V2 V4 V8 V5 V6 V3 V7
Empty
Pop
V1
Not found
V1V2 V4 V8 V5 V6 V3 V7
Empty
The Breadth First Search ( BFS ) is the level-wise traversal of a graph. In the Breadth
first search method, we start at vertex v. Then all unvisited vertices w adjacent to v are
10 - 18
Graphs
visited. Then the unvisited vertices adjacent to w are visited and so on. The process
continues till there are no more unvisited adjacent vertices left to visit.
For the above graph in Fig 3.12, BFS will yield
V1, V2, V3, V4, V5, V6, V7, V8
We require a queue to implement BFS. The method of BFS is very simple. Starting with a
vertex v, we add it to the queue. Remove v from the queue and display. All its adjacent
unvisited vertices are added to the queue. These are removed one-by-one from the queue
and their adjacent unvisited vertices are added to the queue. The process continues till the
queue becomes empty.
Algorithm
1.
2.
3.
Q is an empty queue.
4.
Visited [v] = 1
5.
Add v to queue
6.
7.
8.
9.
Stop
The steps can be shown as follows for the graph in Fig 10.11.
v
V1
V1
V2 V3
Visited
Queue
V1
V1
V1 V2 V3
V2 V3
10 - 19
Graphs
V2
V4 V5
V1V2 V3V4 V5
V3V4 V5
V3
V6 V7
V1V2 V3V4 V5 V6 V7
V4 V5 V6 V7
V4
V8
V1V2 V3V4 V5 V6 V7 V8
V5 V6 V7 V8
V5
Not found
V1V2 V3V4 V5 V6 V7 V8
V6 V7 V8
V6
Not found
V1V2 V3V4 V5 V6 V7 V8
V7 V8
V7
Not found
V1V2 V3V4 V5 V6 V7 V8
V8
V8
Not found
V1V2 V3V4 V5 V6 V7 V8
Empty
We can also perform BFS for a graph stored as an adjacency list. The following program
illustrates this.
APPLICATIONS OF GRAPHS
Graphs can be used in various applications like
i.
ii.
iii.
iv.
v.
vi.
Computing project completion time, delays, early start and late finish times for a
project, which is made up of several tasks.
vii.
Computing the critical path in an AOE (Activity on Edge) Network using CPM
( Critical Path Method).
viii.
10 - 20
Graphs
We will be studying some of the most commonly used applications of a graph. Finding
the Minimal Spanning tree in a graph and Computing the Shortest Path.
Spanning Trees
If G is a graph containing n vertices, then the minimum number of edges needed to
connect the n vertices = n-1. All connected graphs with n-1 edges are trees. These are
called spanning trees.
Definition of Spanning Tree : Let G = (V, E) be an undirected connected graph. A
subgraph t = (V, E) of G is a spanning tree of G iff t is a tree.
A minimum spanning tree is a spanning tree with the lowest number of edges.
10 - 21
Graphs
For example, the vertices of graph G may represent cities and the edges may represent
the roads linking these cities. In order to connect all cities, we will need n-1 links. However,
there may be many feasible combinations of the total n-1 links. Thus, a graph may have
many spanning trees as seen below.
The spanning tree resulting from a call to DFS is known as the DFS spanning tree. The
edges of G traversed by the DFS method form a spanning tree.
BFS Spanning Tree
The spanning tree resulting from a call to BFS is known as the BFS spanning tree. The
edges of G traversed by the BFS method form a spanning tree.
If the starting vertex is V1, The DFS of this graph is V1 V2 V5 V3 V6 V4 and the BFS is V1
V2 V3 V4 V5 V6
In practical situations, the edges will have some weights associated with them. These
may be the distance of the link, Cost of construction etc. Thus, we may want to select the set
of edges which will result in lowest cost of construction or having minimum total length.
Hence we are interested in finding out the spanning tree having minimum total cost.
A minimum Cost spanning tree is a spanning tree whose sum of costs of the edges is
minimum.
10 - 22
Graphs
We shall be studying two algorithms for finding the Minimum Cost Spanning tree.
1.
1.
Prims Algorithm
2.
Kruskals Algorithm
Prims Algorithm
This algorithm builds the minimum cost spanning tree edge by edge. The edge to be
included in the tree T is chosen according to some optimization criteria. The criterion used
here, is to select the edge (u,v) having the smallest cost such that (u,v) is not already in the
tree and T U {(uv)} is also a tree. While including (u,v) we must ensure that it does not
form a cycle. The edge addition is repeated till T contains n1 edges.
What is done in the Prims method is to select a previously unselected edge having the
lowest weight. If it does not form a cycle in the graph, it is added to the tree otherwise it is
rejected. The edge added to the tree is marked as visited so that it is not selected again. The
process completes when we have added n-1 edges to the tree.
Let us apply this method to the following graph to obtain its minimum cost spanning
tree.
20
v1
v2
8
7
v
3
v7
v6
15
11
v5
9
v4
10
Step
Consider
Select
Spanning Tree
v1
1.
(V1, V6)
(V1, V6)
v6
10 - 23
Graphs
v1
2.
(V1, V2),
(V5, V6)
(V5, V6)
v6
v5
15
v1
3.
4
(V4, V5)
v6
v4
v5
15
10
v1
4.
(V3, V4)
v3
4
6
v6
15
v5
v1
5.
(V2, V3)
v4
10
v2
8
v3
4
6
v6
15
v5
v4
10
10 - 24
Graphs
v1
v2
7
6.
(V2, V7)
v7
v6
7.
8.
9.
v3
15
(V4, V7)
Forms a cycle
(V5, V7)
(V1, V2)
Forms a cycle
Forms a cycle
v5
6
v4
10
2.
Kruskals Algorithm
In the Prims algorithm studied earlier, at any stage, the set of selected edges must form
a tree.
In the Kruskals algorithm, however, the set of edges may not be a tree at all stages. The
set will generally be a forest and can be completed into a tree iff there are no cycles in the
set. The edges will be considered one by one such that it has minimum cost among the
remaining edges and does not form a cycle.
10 - 25
Graphs
The method is simple. The spanning tree T is constructed edge by edge. We select the
edges one-by-one. We select an unvisited edge having smallest cost and add it to the
partially complete spanning tree. If the edge forms a cycle, it is not considered. When n-1
edges have been added to the spanning tree, the process stops.
Example
20
v1
v2
8
v3
7
4
v7
11
v6
15
v5
9
v4
10
Step
1
Consider
(V1, V6)
Spanning Tree
v1
v2
v3
2.
(V3, V4)
v7
v6
v5
v1
v2
v4
v3
4
v7
6
v6
v5
v4
10 - 26
Graphs
3.
(V2, V7)
v2
v1
v3
7
4
v7
6
4.
(V2, V3)
v6
v5
v1
v2
v4
8
v3
7
4
v7
6
v6
5.
6.
(V4, V7)
(V4, V5)
v4
v5
v2
v1
8
v3
7
4
v7
6
v6
7.
8.
(V5, V7)
(V5, V6)
v5
v4
10
v2
v1
8
v3
7
4
v7
6
v6
15
v5
v4
10
10 - 27
Graphs
AlgorithmKruskal(E,cost,n)
{
T=0;/*startwithaTreehavingnoedges*/
While(Tcontainslessthann1edgesandEisnotempty)
{
chooseedge(u,v)fromEsuchthatcost[u,v]isminimum
delete (u,v)fromE
if(u,v)doesnotcreateacycleinT
add(u,v)toT
else
discard(u,v)
}
if(Tcontainsfewerthann1edges)
Printnospanningtree
}
Comparing Prims and Kruskals Algorithm
Both produce identical trees when edge weights are distinct. When G is connected,
Kruskals algorithm cannot produce a forest. When no weights are equal, then random edge
selection cannot occur.
Shortest Path
Graphs may be used to represent the road network of a state or country with the vertices
representing cities and the edges representing the connecting roads. Each edge may be
assigned a weight, which may be the distance between the two vertices or the time taken to
go from one vertex to another.
A person wishing to travel from city A to city B could require the following information.
i.
ii.
gives the shortest paths from a given vertex (source) to all other vertices in the network.
Inputs
1.
This algorithm takes the input graphs in the form of a cost matrix which is an
adjacency matrix with each element,
A[i] [j]
10 - 28
Graphs
2.
visited is an array of n elements which indicates whether a vertex has been visited or
not.
3.
dist is an array of n elements which stores the distances of all vertices from the source
vertex.
Algorithm
1.
2.
3.
4.
visited[v] = 1
5.
num = 1
6.
if (! visited[w])
if (dist[u] + cost[u][w]<dist[w])
dist[w] = dist[u]+cost[u][w]
}
}
7.
dist array contains the shortest paths from V to all other destinations.
8.
Stop
Analysis
In this algorithm , the dist array initially contains distances from v to all the vertices
which are adjacent to it. The remaining are .
In the next steps, we select a vertex u, which is closest to v. Using u, find out the
distances from v to the vertices w, which are connected to u . Compare the distance vw
and distance (vu)+(uw). If this new distance happens to be less than the distance in the
distance array (vw), the new distance is put in the array. This means that there is a
10 - 29
Graphs
shorter path to a vertex w (which is adjacent to u) from vertex u as compared to the current
path from (vw)
The process continues till all vertices have been considered.
Note: This algorithm only gives the shortest distances from starting vertex v to all other
vertices. It does not store the paths to these vertices. For that, we will have to use some
additional logic.
Example: Consider the 8 vertex digraph (directed graph) with cost adjacency matrix as
shown
80
30
120
2
150
100
100
V
25
V
170
40
90
V
100
Weighted graph
0
0
30
100
80
170
120
150
25
100
90
140
100
Visited
Remarks
Dist Array
0
150
25
125
25
115
165
4,5
125
25
115
165
No change via 6
165
4,5,6
245
125
25
115
10 - 30
Graphs
245 125 0
25
115
165
4,5,6,3
335
4,5,6,3,7
335
325
245
125
25
115
165
4,5,6,3,7,2
335
325
245
125
25
115
165
No change via 1
4,5,6,3,7,2,1
335
325
245
125
25
115
165
No change via 0
4,5,6,3,7,2,1,0
335
325
245
125
25
115
165
Topological Sort
Graphs are commonly used for project planning which consists of many interdependent
activities. These activities are represented as vertices and the directed edges represent the
order of the activities. Such a graph is called an Activity on Vertex (AOV) network.
AOV network: A directed graph in which the vertices represent activities or tasks and
the edges represent the precedence is called an AOV network.
Vertex i in an AOV network is a predecessor of vertex j if there is a directed path from i
to j. This means that unless activity i is completed, j cannot be performed. There should be
no cycles in an AOV network i.e there should be atleast one activity which does not have a
predecessor.
Example
V
V
n o t f e a s i b le
f e a s ib le
AOV networks
In the first AOV network, V1 does not have any predecessor and hence it is the starting
activity.
In the second network, there is a cycle i.e. each activity is dependent on some other
activity. Hence the project represented by this graph is not feasible.
10 - 31
Graphs
Topological Sort
If we have an AOV network, then we would like to find out whether the project is feasible
or not and if it is feasible, then in what order should the activities be performed so that the
project can be completed. This can be done using a method called the Topological Sort.
The process of converting a set of precedences represented by an AOV network into a
linear list in which no later activity precedes an earlier one is called Topological Sorting.
This method identifies the order of the activities.
The process is very simple. We start with the activity / activities having no predecessor
i.e. having indegree 0. These are then marked as visited and pushed into a stack. We then
pop an activity from the stack, find out the activities dependent on this activity and reduce
their indegrees by 1. The same process repeats again till all the activities have been visited
and the stack is empty.
Algorithm
1.
2.
S is an empty stack
3.
4.
if v is found
mark v as visited
make indegree of v = 1
push v into stack
5. If v is not found
If stack is empty
Go to 7
Else
pop v from the stack and display.
Reduce the indegree of all vertices adjacent to v by 1.
6.
8. Stop.
10 - 32
Graphs
Since we need the indegree of the vertices, the node structure has to be modified. Each
list will have a head node which also stores the indegree of the vertex. We can use the first
node of each list to store the indegrees.
Example
A d ja c e n c y lis t
In d e g re e p tr
A O V n e tw o rk
V
V
NU LL
N ULL
NU LL
N U LL
N U LL
AOV network
Vertex
considered
No.
Indegrees
Stack
V1
V2
V3
V4
V5
V1
-1
v1
2.
None
-1
Empty
-1
-1
-1
V2,V3
-1
-1
-1
V2
1, 3
-1
-1
-1
Empty
1,3, 2
3.
V2, v3
None
4.
5.
None
6.
V4
-1
-1
-1
-1
V4
5.
None
-1
-1
-1
-1
Empty
6.
V5
-1
-1
-1
-1
-1
V5
7.
None
-1
-1
-1
-1
-1
Empty
Remarks
Display
1,3,2 ,4
1,3,2,4,5
10 - 33
Graphs
PROBLEMS
1. Find the indegree and outdegree of every vertex in the following graph.
2
4
6
1
3
Soln:
Vertex
1
2
3
4
5
6
Indegre
0
1
1
2
2
2
Outdegree
2
2
2
1
1
0
1
0
0
0
1
0
0
0
1
1
0
0
Soln: Since the matrix is of size 4 X 4, there are 4 vertices. Let us number them V 1 to V4.
There are 3 vertices connected to V1 and one vertex connected to V2 . Hence the graph will
look like :
V
V
10 - 34
Graphs
3. From the following adjacency list representation of a graph, draw the graph.
NULL
NULL
NULL
NU LL
NULL
5. Draw the minimum cost spanning tree obtained for the following graph using Prim s
algorithm.
16
v1
v3
8
10
12
v4
5
v2
20
4
14
v6
9
v5
Soln: The steps for the minimum cost spanning tree using Prims algorithm are as follows.
There are 6 vertices. Hence the spanning tree will contain 5 edges.
Step
1.
2.
3.
4.
5.
6.
Consider
(V4, V5)
(V2, V4)
(V3, V5)
(V3, V4)
(V5, V6)
(V1, V2)
Action
Select
Select
Select
Reject
Select
Select
6. Find the shortest paths to all vertices in the following graph from vertex 1 as the source
vertex. Show all steps.
10 - 35
Graphs
1
10
40
30
10
50
3
60
4
20
Soln: The cost adjacency matrix for the above graph is to be used.
1
1
0
2
10
2
3
4
30
5
40
10
50
50
20
10
30
20
60
40
10
20
The distance array shows current distances from vertex 1 to all other vertices
Dist
1
0
2
10
4
30
5
40
1
0
2
10
3
60
4
30
5
40
1
0
2
10
3
50
4
30
5
40
Dist
1
0
10 - 36
Graphs
2
3
10 50
4
30
5
40
4
30
5
40
1
0
2
10
3
50
ii)
iii)
iv)
v)
Soln:
i)
Adjacency Matrix
1
2
3
4
5
6
1
0
1
0
0
1
1
2
0
0
1
0
0
1
3
0
0
0
1
0
0
4
0
1
0
0
0
0
5
0
0
0
1
0
1
6
0
0
1
1
0
0
ii)
Vertex
1
2
Indegre
3
2
Outdegree
0
2
10 - 37
Graphs
3
1
4
1
5
2
6
2
BFS = 2, 1, 4, 3, 5, 6.
2
3
1
3
iii)
DFS = 2, 1, 4, 3, 6,5
iv)