Unit Iv Non Linear Data Structures - Graphs
Unit Iv Non Linear Data Structures - Graphs
Types of Graphs
Graphs are of two types
Directed graphs.
Undirected Graphs.
In Directed graph, the edges between the vertices are ordered. E1 is the edge between the
vertices V1 and V2.
V1 is called the Head and V2 is called the Tail.
So, E1 is a set of (V1, V2) and not of (V2, V1).
111
CS8391 DATA STRUCTURES UNIT - IV
In Undirected graph, the edges between the vertices are not ordered.
So, E1 is a set of (V1, V2) or (V2, V1).
Adjacent nodes : two nodes are adjacent if they are connected by an edge
Path: a sequence of vertices that connect two nodes in a graph
Length of path of graph: is the number of edges in the path
In-degree of a node x in G is the number of edges coming to x.
Out-degree of x is the number of edges leaving x.
Weighted Graphs:
A graph is said to be weighted graph if every edge in the graph is assigned a weight or value.
It can be either a directed or an undirected graph.
A complete graph is a graph in which there is an edge between every pair of vertices.
A complete graph with n vertices will have n(n - 1) /2 edges.
112
CS8391 DATA STRUCTURES UNIT - IV
Sub Graph
A sub graph G’ of G is a graph G such that the set of vertices and set of edges of G’ are
proper subset of the set of edges of G.
Connected Graphs
An undirected graph is said to be connected if for every pair of distinct vertices Vi and Vj,
there is a path from Vi to Vj in G.
Cyclic Graphs
A directed graph is said to be a cyclic graph in which no vertex is repeated except the first
and last vertex are the same.
113
CS8391 DATA STRUCTURES UNIT - IV
An undirected graph is said to be a cyclic graph in which if any edge appears more than once
it appears with the same orientation.
Acyclic Graphs
A graph is said to be a acyclic graph if it has no cycles.
114
CS8391 DATA STRUCTURES UNIT - IV
For each edge of the graph (Vi, Vj), the location of the matrix at row i and column j is 1
All other locations are 0
For an undirected graph, the matrix will be symmetric along the diagonal
For a weighted graph, the adjacency matrix would have the weight for edges in the graph,
zeros along the diagonal, and infinity (∞) every place
Advantage
Simple to implement
Easy and fast to tell if a pair (i,j) is an edge: simply check if A[i][j] is 1 or 0
Disadvantage
Even if there are few edges, the matrix takes O(n2) in memory
Graph traversal is technique used for searching a vertex in a graph. The graph traversal is
also used to decide the order of vertices to be visit in the search process. A graph traversal finds
the egdes to be used in the search process without creating loops that means using graph traversal
we visit all verticces of graph without getting into looping path.
There are two graph traversal techniques and they are as follows...
BFS traversal of a graph, produces a spanning tree as final result. Spanning Tree is a graph
without any loops. We use Queue data structure with maximum size of total number of vertices
in the graph to implement BFS traversal of a graph.
115
CS8391 DATA STRUCTURES UNIT - IV
Step 2: Select any vertex as starting point for traversal. Visit that vertex and insert it into
the Queue.
Step 3: Visit all the adjacent vertices of the verex which is at front of the Queue which is
not visited and insert them into the Queue.
Step 4: When there is no new vertex to be visit from the vertex at front of the Queue then
delete that vertex from the Queue.
Step 6: When queue becomes Empty, then produce final spanning tree by removing unused
edges from the graph
Example:
116
CS8391 DATA STRUCTURES UNIT - IV
117
CS8391 DATA STRUCTURES UNIT - IV
#include<stdio.h>
#include<conio.h>
int a[20][20],q[20],visited[20],n,i,j,f=0,r=-1;
void bfs(int v) {
for (i=1;i<=n;i++)
if(a[v][i] && !visited[i])
q[++r]=i;
if(f<=r) {
visited[q[f]]=1;
bfs(q[f++]);
}
}
void main() {
int v;
clrscr();
printf("\n Enter the number of vertices:");
scanf("%d",&n);
for (i=1;i<=n;i++) { III
q[i]=0;
visited[i]=0;
}
printf("\n Enter graph data in matrix form:\n");
for (i=1;i<=n;i++)
for (j=1;j<=n;j++)
scanf("%d",&a[i][j]);
printf("\n Enter the starting vertex:");
scanf("%d",&v);
bfs(v);
printf("\n The node which are reachable are:\n");
for (i=1;i<=n;i++)
if(visited[i])
printf("%d\t",i); else
printf("\n Bfs is not possible");
getch();
}
Output:
Enter Number of Vertices:4
Enter graph data in Matrix form:
1 0 1 0
0 0 1 1
0 1 0 1
1 1 1 1
1 2 3 4
Step 2: Select any vertex as starting point for traversal. Visit that vertex and push it on to
the Stack.
Step 3: Visit any one of the adjacent vertex of the verex which is at top of the stack which is
not visited and push it on to the stack.
120
CS8391 DATA STRUCTURES UNIT - IV
Step 4: Repeat step 3 until there are no new vertex to be visit from the vertex on top of the
stack.
Step 5: When there is no new vertex to be visit then use back tracking and pop one vertex
from the stack.
Step 7: When stack becomes Empty, then produce final spanning tree by removing unused
edges from the graph
Example:
121
CS8391 DATA STRUCTURES UNIT - IV
122
CS8391 DATA STRUCTURES UNIT - IV
123
CS8391 DATA STRUCTURES UNIT - IV
124
CS8391 DATA STRUCTURES UNIT - IV
#include<stdio.h>
#include<conio.h>
int a[20][20],reach[20],n;
void dfs(int v)
{
int i;
reach[v]=1;
for (i=1;i<=n;i++)
if(a[v][i] && !reach[i])
{
printf("\n %d->%d",v,i);
dfs(i);
}
}
void main()
{
int i,j,count=0;
clrscr();
printf("\n Enter number of vertices:");
scanf("%d",&n);
for (i=1;i<=n;i++)
{
reach[i]=0;
for (j=1;j<=n;j++)
a[i][j]=0;
125
CS8391 DATA STRUCTURES UNIT - IV
}
printf("\n Enter the adjacency matrix:\n");
for (i=1;i<=n;i++)
for (j=1;j<=n;j++)
scanf("%d",&a[i][j]);
dfs(1);
printf("\n");
for (i=1;i<=n;i++) {
if(reach[i])
count++;
}
if(count==n)
printf("\n Graph is connected"); else
printf("\n Graph is not connected");
getch();
}
OUTPUT:
Enter Number of Vertices:4
Enter the Adjacency Matrix:
0 1 0 1
1 1 1 1
0 1 1 0
0 1 1 1
12
23
24
Graph is connected
Algorithm:
1. From a given graph find a vertex with no incoming edges. Delete it along with an the
edges outgoing from it. If there are more than one such vertices then break the tie
randomly.
2. Note the vertices that are deleted.
3. All these recorded vertices give topologically sorted list.
Example 1: A C
B D
126
CS8391 DATA STRUCTURES UNIT - IV
Choose vertex B, because it has no incoming edge, delete it along with its adjacent edges.
Delete B A C
C
E Delete A
Delete D
E
D
D
Sorted List B
Sorted List B, A
C Delete C
Delete E
E
E Sorted List B, A, D, C, E
127
CS8391 DATA STRUCTURES UNIT - IV
Definition:
A vertex V is an Undirected graph G is called a cut vertex if removing it disconnects the graph.
The cut vertex is also called as articulation point.
The following example represents the concept of cut vertex.
128
CS8391 DATA STRUCTURES UNIT - IV
A E
C G
B F
A E
B D F
Euler Path:
A Path in a graph G is Called Euler Path if it includes every edge exactly once and every
vertex gets visited.
Euler Circuit on graph G is an Euler path that visits each vertex of graph G and uses
every edge of G.
129
CS8391 DATA STRUCTURES UNIT - IV
B
For Example
A C
E D
Fig: 4.13 Euler Circuit
In Computer networking such as Local Area Network (LAN), Wide Area Networking
(WAN), internetworking.
In Telephone cabling graph theory is effectively used
In Job Scheduling algorithm
The single source shortest path algorithm 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.
All pairs shortest path problem finds the shortest distance from each vertex to all other vertices.
To solve this problem dynamic programming technique known as floyd’s algorithm is used.
These algorithms are applicable to both directed and undirected weighted graphs provided
that they do not contain a cycle of negative length.
130
CS8391 DATA STRUCTURES UNIT - IV
The Dijkstra's shortest path algorithm suggests the shortest path from some source node to
the some other destination node. The source node or the node from we start measuring the
distance is called the start node and the destination node is called the end node. In this algorithm
we start finding the distance from the start node and find all the paths from it to neighbouring
nodes. Among those which ever is the nearest node that path is selected. This process of finding
the nearest node is repeated till the end node. Then whichever is the path that path is called the
shortest path.
Since in this algorithm all the paths are tried and then we are choosing the shortest path
among them, this algorithm is solved by a greedy algorithm. One more thing is that we are
having all the vertices in the shortest path and therefore the graph doesn't give the spanning tree.
Example:
Step 1:
v=a
P = {a}, T = {b,c,d,e,f,z}
dist(b) = min[old dist(b),dist(a)+w(a,b)]
dist(b) = min[∞,0+22|
dist(b) = 22
dist(c) = 16
dist(d)= 8 ← minimum node
dist(e) = ∞
dist(f) = ∞
dist(z) = ∞
So minimum node is selected in P i.e. node d.
Step 2 :
v=d
P = {a,d} T = {b,c,e,f,z}
dist(b) = min{old dist(b),dist(d)+w(b,d)}
dist(b) = min{22,8+∞}
dist(b) = 22
dist(c) = min{16,8+10} = 16
dist(e) = min{∞,8+∞} = 8
dist(f) = min{∞,8+6} = 14
dist(z) = min{∞,8+∞} = ∞
131
CS8391 DATA STRUCTURES UNIT - IV
Step 3 :
v=f
P = {a,d,f} T = {b,c,e,z}
dist(b) = min{22,14+7} = 21
dist(c) = min{16,14+3} = 16
dist(e) = min{ ∞,14 +∞ } = ∞
dist(z) = min{∞, 14+9) = 23
Step 4 :
v=c
P = {a,d,f,c} T = {b,e,z}
dist(b)= min{21,16+20} = 21
dist(e) = min{∞ ,16+4}= 20
dist(z) = min{23,16+10} = 23
Step 5:
v=e
P = (a,d,f,c,e( T = |b,z|
dist(b) =min|21,20+2| = 21
dist(z) =min|23,20+4)= 23
Step 6:
v=b
P = (a,d,f,c,e,b) T = (z)
dist(z) = min(23,21+2) = 23.
Now the target vertex for finding the shortest path is z. Hence the length of the shortest path
from the vertex a to z is 23. The shortest path shown below
PART A
132
CS8391 DATA STRUCTURES UNIT - IV
TOPOLOGICAL SORT
PART-B
133
CS8391 DATA STRUCTURES UNIT - IV
PART A
1. Define graph.
A graph is a collection of two sets of V and E where V is finite non empty set of vertices and
E is a finite non empty set of edges.
Vertices are nothing but the nodes in the graph and two adjacent vertices are joined by edges.
The graph is denoted by G = {V, E}.
Example:
Example:
Example:
134
CS8391 DATA STRUCTURES UNIT - IV
Example:
Example:
Example:
Example:
135
CS8391 DATA STRUCTURES UNIT - IV
10. What does traversing a graph mean? State the different ways of traversing a graph.
Traversing a graph means visiting all the nodes in the graph. The two important graph
traversal methods are
Depth first traversal or depth first search (DFS)
Breadth first traversal or breadth first search (BFS)
Number of vertices is 4
Number of edges is 6
136
CS8391 DATA STRUCTURES UNIT - IV
Indegree(V1) = 1
Indegree(V2) = 1
Outdegree(V3) = 1
Outdegree(V4) = 1
TOPOLOGICAL SORT
138
CS8391 DATA STRUCTURES UNIT - IV
29. What is the minimum number of spanning trees possible for a complete graph with n
vertices?
There are nn-2 number of spanning trees for a complete graph with n vertices. For example if
there are 3 vertices in a complete graph i.e. K3 then there are 33-2=3 spanning trees possible.
139