You are on page 1of 29

Department of Humanities and Sciences Data Structures

Dr.B. Srinivasa Rao


UNIT-V
Graphs: Definition, Basic Terminology, Representation of Graphs, Graph
Traversal Techniques –
Breadth First Traversal, Depth First Traversal.

Definition:

A Graph is a non-linear data structure consisting of nodes and edges. The nodes are
sometimes also referred to as vertices and the edges are lines or arcs that connect any
two nodes in the graph.

More formally a Graph can be defined as, A graph consists of a finite set of vertices
and set of edges which connect a pair of nodes.

In the above Graph, the set of vertices V = {0,1,2,3,4} and the set of edges E = {01,
12, 23, 34, 04, 14, 13}.

Applications

1. Graphs are used to represent networks which include paths in a city or telephone
network or circuit network.
Department of Humanities and Sciences Data Structures
Dr.B. Srinivasa Rao
2. Graphs are also used in social networks like linkedIn, Facebook. For example, in
Facebook, each person is represented with a vertex(or node). Each node is a structure
and contains information like person id, name, gender, locale etc.

Types of Graphs

1. Undirected Graph: An Undirected graph is a graph in which edges have no


orientation. The edge (x,y) is identical to edge (y,x) i.e., they are not ordered pairs.
The maximum number of edges possible in an undirected graph without loop is n
*(n-1)/2

2. Directed Graph: A Directed graph is a graph in which edges have orientation.


The edge (x,y) is not identical to edge (y,x) .
Department of Humanities and Sciences Data Structures
Dr.B. Srinivasa Rao
3. Directed Acyclic graph: A directed acyclic graph is a directed graph that has no
cycles

4. Multi Graph: A multi graph is an undirected graph in which multiple edges are
allowed. Multiple edges are two or more edges that connect the same two vertices.
A loop is an edge that connect an edge to itself

5. Simple Graph: a simple graph is an undirected graph in which both multiple


edges and loops are disallowed as opposed to a multi graph. In a simple graph with
n vertices, every vertex’s degree is at most n-1
Department of Humanities and Sciences Data Structures
Dr.B. Srinivasa Rao
6. Weighted and Un weighted Graph: A weighted graph associates a value with
every edge in the graph. An un weighted graph does not have any value associated
with every edge in the graph. If weight is not specified then its value is 1.

7. Complete Graph: A complete graph is one in which every two vertices are
adjacent

8. Connected Graph: A connected graph has a path between every pair of vertices.
In other words, there are no unreachable vertices. A disconnected graph is a graph
that is not connected.
Department of Humanities and Sciences Data Structures
Dr.B. Srinivasa Rao

Basic Terminology:

 An edge is (together with vertices) one of the two basic units out of
which graphs are constructed. Each edge has two vertices to which it
is attached, called its endpoints.
 Two vertices are called adjacent if they are endpoints of the same
edge.
 Outgoing edges of a vertex are directed edges that the vertex is the
origin.
 Incoming edges of a vertex are directed edges that the vertex is the
destination.
 The degree of a vertex in a graph is the total number of edges incident
to it.
 In a directed graph, the out-degree of a vertex is the total number of
outgoing edges, and the in-degree is the total number of incoming
edges.
 A vertex with in-degree zero is called a source vertex, while a vertex
with out-degree zero is called a sink vertex.
Department of Humanities and Sciences Data Structures
Dr.B. Srinivasa Rao
 An isolated vertex is a vertex with degree zero, which is not an

endpoint of an edge.
 Path is a sequence of alternating vertices and edges such that the
edge connects each successive vertex.
 Cycle is a path that starts and ends at the same vertex.
 Simple path is a path with distinct vertices.
 A graph is Strongly Connected if it contains a directed path
from  u  to  v  and a directed path from  v  to  u  for every pair of

vertices  u ,  v .

 A directed graph is called Weakly Connected if replacing all of its


directed edges with undirected edges produces a connected
(undirected) graph. The vertices in a weakly connected graph have
either out-degree or in-degree of at least 1.
 Connected component is the maximal connected subgraph of an
unconnected graph.
 A bridge is an edge whose removal would disconnect the graph.
 Forest is a graph without cycles.
 Tree is a connected graph with no cycles. If we remove all the cycles
from DAG (Directed Acyclic Graph), it becomes a tree, and if we
remove any edge in a tree, it becomes a forest.
 Spanning tree of an undirected graph is a subgraph that is a tree that
includes all the vertices of the graph.
Department of Humanities and Sciences Data Structures
Dr.B. Srinivasa Rao

Relationship between number of edges and vertices

For a simple graph with  m  edges and  n  vertices, if the graph is

 directed, then  m = n×(n-1)

 undirected, then  m = n×(n-1)/2

 connected, then  m = n-1

 a tree, then  m = n-1

 a forest, then  m = n-1

 complete, then  m = n×(n-1)/2

Therefore, O(m) may vary between O(1) and O(n2), depending on how


dense the graph is.
Department of Humanities and Sciences Data Structures
Dr.B. Srinivasa Rao

Representation of Graphs
1. Adjacency Matrix Representation:
An adjacency matrix is a square matrix used to represent a finite graph. The
elements of the matrix indicate whether pairs of vertices are adjacent or not
in the graph.

Definition:
For a simple unweighted graph with vertex set  V , the adjacency matrix is a
square  |V| × |V|  matrix  A  such that its element:
A ij  = 1 , when there is an edge from vertex  i  to vertex  j , and
A ij  = 0 , when there is no edge.

Each row in the matrix represents source vertices, and each column
represents destination vertices. The diagonal elements of the matrix are all
zero since edges from a vertex to itself, i.e., loops are not allowed in simple
graphs. If the graph is undirected, the adjacency matrix will be symmetric.
Also, for a weighted graph,  A ij can represent edge weights.
Row i= 0 1 2 3 4 5; Column j=0,1,2,3,4,5:

 
Department of Humanities and Sciences Data Structures
Dr.B. Srinivasa Rao
An adjacency matrix keeps a value  (1/0/edge-weight)  for every pair of
vertices, whether the edge exists or not, so it requires  n 2 space. They can
be efficiently used only when the graph is sparse (or dense).

2. Adjacency List Representation:

An adjacency list representation for the graph associates each vertex in the
graph with the collection of its neighboring vertices or edges, i.e.,

Every vertex stores a list of adjacent vertices. There are many variations of
adjacency list representation depending upon the implementation. This data
structure allows the storage of additional data on the vertices but is
practically very efficient when the graph contains only a few edges.

 
Department of Humanities and Sciences Data Structures
Dr.B. Srinivasa Rao

Graph Traversal Techniques


Breadth First Traversal: -

It traverses a graph in a breadth ward motion and uses a queue to


remember to get the next vertex to start a search, when a dead end occurs
in any iteration.

GFEDCBA

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


F first then to C and G lastly to D. It employs the following rules.
Department of Humanities and Sciences Data Structures
Dr.B. Srinivasa Rao
 Rule 1 − Visit the adjacent unvisited vertex. Mark it as visited. Display

it. Insert it in a queue.


 Rule 2 − If no adjacent vertex is found, remove the first vertex from the
queue.
 Rule 3 − Repeat Rule 1 and Rule 2 until the queue is empty.

Step Traversal Description

Initialize the queue.

2
We start from
visiting S (starting node),
and mark it as visited.
Department of Humanities and Sciences Data Structures
Dr.B. Srinivasa Rao
3
We then see an unvisited
adjacent node from S. In
this example, we have
three nodes but
alphabetically we
choose A, mark it as
visited and enqueue it.

4
Next, the unvisited
adjacent node
from S is B. We mark it
as visited and enqueue it.

5
Next, the unvisited
adjacent node
from S is C. We mark it
as visited and enqueue it.
Department of Humanities and Sciences Data Structures
Dr.B. Srinivasa Rao
6
Now, S is left with no
unvisited adjacent nodes.
So, we dequeue and
find A.

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

At this stage, we are left with no unmarked (unvisited) nodes. But as per the
algorithm we keep on dequeuing in order to get all unvisited nodes.

When the queue gets emptied, the program is over.

Program for BFS Traversal of a Graph

#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) {
Department of Humanities and Sciences Data Structures
Dr.B. Srinivasa Rao
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("Enter the number of vertices: ");

scanf("%d",&n);

for(i=1; i <= n; i++) {

q[i] = 0;

visited[i] = 0;

printf("\nEnter graph data in matrix form:\n");


Department of Humanities and Sciences Data Structures
Dr.B. Srinivasa Rao
for(i=1; i<=n; i++) {

for(j=1;j<=n;j++) {

scanf("%d", &a[i][j]);

printf("Enter the starting vertex: ");

scanf("%d", &v);

bfs(v);

printf("\nThe node which are reachable are:");

for(i=1; i <= n; i++) {

if(visited[i])

printf(" %d", i);

else {

printf("\nBFS is not possible. All nodes are not reachable!");

break;

getch();
Department of Humanities and Sciences Data Structures
Dr.B. Srinivasa Rao
}

Depth First Traversal.

It traverses a graph in a depth ward motion and uses a stack to remember


to get the next vertex to start a search, when a dead end occurs in any
iteration.

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


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

 Rule 1 − Visit the adjacent unvisited vertex. Mark it as visited. Display
it. Push it in a stack.

 Rule 2 − If no adjacent vertex is found, pop up a vertex from the stack.
(It will pop up all the vertices from the stack, which do not have
adjacent vertices.)
Department of Humanities and Sciences Data Structures
Dr.B. Srinivasa Rao
 Rule 3 − Repeat Rule 1 and Rule 2 until the stack is empty.

Ste Traversal Description


p

Initialize the stack.

2 Mark S as visited and


put it onto the stack.
Explore any unvisited
adjacent node
from S. We have
three nodes and we
can pick any of them.
For this example, we
shall take the node in
an alphabetical
order.
Department of Humanities and Sciences Data Structures
Dr.B. Srinivasa Rao
3 Mark A as visited
and put it onto the
stack. Explore any
unvisited adjacent
node from A.
Both S and D are
adjacent to A but we
are concerned for
unvisited nodes only.

4 Visit D and mark it as
visited and put onto
the stack. Here, we
have B and C nodes,
which are adjacent
to D and both are
unvisited. However,
we shall again
choose in an
alphabetical order.
Department of Humanities and Sciences Data Structures
Dr.B. Srinivasa Rao
5 We choose B, mark it
as visited and put
onto the stack.
Here B does not
have any unvisited
adjacent node. So,
we pop B from the
stack.

6 We check the stack


top for return to the
previous node and
check if it has any
unvisited nodes.
Here, we find D to be
on the top of the
stack.

7 Only unvisited
adjacent node is
from D is C now. So
we visit C, mark it as
visited and put it onto
Department of Humanities and Sciences Data Structures
Dr.B. Srinivasa Rao
the stack.

As C does not have any unvisited adjacent node so we keep popping the
stack until we find a node that has an unvisited adjacent node. In this case,
there's none and we keep popping until the stack is empty.

#include <stdio.h>

#include <stdlib.h>

/* ADJACENCY MATRIX */

int source,V,E,time,visited[20],G[20][20];

void DFS(int i)

int j;

visited[i]=1;

printf(" %d->",i+1);

for(j=0;j<V;j++)

if(G[i][j]==1&&visited[j]==0)

DFS(j);

int main()
Department of Humanities and Sciences Data Structures
Dr.B. Srinivasa Rao
{

int i,j,v1,v2;

printf("\t\t\tGraphs\n");

printf("Enter the no of edges:");

scanf("%d",&E);

printf("Enter the no of vertices:");

scanf("%d",&V);

for(i=0;i<V;i++)

for(j=0;j<V;j++)

G[i][j]=0;

/* creating edges :P */

for(i=0;i<E;i++)

printf("Enter the edges (format: V1 V2) : ");

scanf("%d%d",&v1,&v2);

G[v1-1][v2-1]=1;

}
Department of Humanities and Sciences Data Structures
Dr.B. Srinivasa Rao

for(i=0;i<V;i++)

for(j=0;j<V;j++)

printf(" %d ",G[i][j]);

printf("\n");

printf("Enter the source: ");

scanf("%d",&source);

DFS (source-1);

return 0;

}
Department of Humanities and Sciences Data Structures
Dr.B. Srinivasa Rao
Department of Humanities and Sciences Data Structures
Dr.B. Srinivasa Rao

Hash Table is a data structure which stores data in an associative manner.


In a hash table, data is stored in an array format, where each data value
has its own unique index value. Access of data becomes very fast if we
know the index of the desired data.

Thus, it becomes a data structure in which insertion and search operations


are very fast irrespective of the size of the data. Hash Table uses an array
as a storage medium and uses hash technique to generate an index where
an element is to be inserted or is to be located from.

Hashing

Hashing is a technique to convert a range of key values into a range of


indexes of an array. We're going to use modulo operator to get a range of
key values. Consider an example of hash table of size 20, and the following
items are to be stored. Item are in the (key,value) format.
Department of Humanities and Sciences Data Structures
Dr.B. Srinivasa Rao
Department of Humanities and Sciences Data Structures
Dr.B. Srinivasa Rao
Department of Humanities and Sciences Data Structures
Dr.B. Srinivasa Rao
Department of Humanities and Sciences Data Structures
Dr.B. Srinivasa Rao
Department of Humanities and Sciences Data Structures
Dr.B. Srinivasa Rao

You might also like