0% found this document useful (0 votes)
17 views9 pages

Unit-5 1

Uploaded by

ramketha07
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)
17 views9 pages

Unit-5 1

Uploaded by

ramketha07
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/ 9

Graphs

A graph is a non linear data structure. There is no hierarchical relationship


between the adjacent elements. Graph consists of following two components:
1. A finite set of vertices also called as nodes.
2. A finite set of ordered pair of the form (u, v) called as edge. The
pair is ordered because (u, v) is not same as (v, u) in case of directed graph

Def: A graph G consists of a set V of vertices (refered as nodes in case of trees)


and a set E of edges. Graph can be denoted as,

G=(V,E), V is a finte and non-empty set of vertices


E is a set of edges i.e set of pair of vertices.

An edge e=(u,v) is a pair of verices and joins two vertices u&v.

Graphs are used to represent many real life applications: Graphs are used to
represent networks. The networks may include paths in a city or telephone
network or circuit network. 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 and locale. This can be easily viewed
by http://graph.facebook.com/vishnul.society where vishnu.society is the profile
name.
Graph Storage representations:
Graph is a mathematical structure and finds its application in many areas of
interest in which problems need to be solved using computers. Thus, this
mathematical structure must be represented in some kind of data structure. Two
such representtions are commonly used. They are,
- Adjacency Matrix representation
- Adjacency List representation

Adjacency Matrix Representation:


A graph containing N vertices can be represented by a matrix with N rows
and N columns. i.e. The adjacency matrix A for a graph G=(V,E) with N vertices
is an N X N array such that
A[i][j] = 1, if there is an edge from vi to vj
= 0 , if there is no edge from vi to vj

 The adjacency matrix for an undirected graph is symmetric; the adjacency


matrix for a digraph need not be symmetric.
 For a weighted graph,
A[i][j] = Weight of the edge, if there is an edge from vi to vj
= 0 , if there is no edge from vi to vj

 In this representation we require n2 elements to represent a graph with n


nodes. The adjacency matrix is a simple way to represent a graph but it
has two disadvantages.
- It takes O(n2) space to represent a graph with n vertices.
- It takes O(n2) time to solve most of the graph problems.
Adjacency List Representation:
In this representation , we store a graph as a linked structure. We store all
the vertices in a linked list (node list) and then for each vertex, we have a linked
list of its adjacent vertices(edge list).
The number of vertices in a graph forms a doubly linked node list. Each
node have a separate linked list, with nodes equal to the number of edges
connected from the corresponding vertex.
Graph Traversals: Traversing a graph means visiting all the nodes in the graph.
In many practical applications, traversing a graph is important, such that each
vertex is visted once systematically by traversing through minimumnumber of
paths. The two important graph traversal methods are,
- Depth-First Traversal (or) Depth First Search (DFS)
- Breadth First Traversal(or) Breadth First Search (BFS)
The BFS will use Queue as an auxilary structure to hold nodes for future
processing where as, the DFS uses stacks.
Depth First Search(DFS):
The procedure of DFS is
1. Select an unvisited node x, visit it, and treat as the current node
2. Find an unvisited neighbor of the current node, visit it, and make it
the new current node;
3. If the current node has no unvisited neighbors, backtrack to the its
parent, and make that parent the new current node;
4. Repeat steps 3 and 4 until no more nodes can be visited.
5. If there are still unvisited nodes, repeat from step 1.
The Depth First Travesral of a graph is much similar to preorder traversal of
an ordered tree. The DFS of a graph start at any arbitrary node, say A. Suppose
B, C, D and E be the nodes adjacent to A then, we will next visit B and keep C, D
and E waiting. After visiting B, we traverse all the vertices to which it is adjacent
before returning to traverse C,D and E.
 In DFS, we backtrack on a path once it reached the end of that path.
Implementation procedure for DFS:
1. All nodes are initialized to ‘unvisited’ state and initialize stack to
empty.
2. Start with any node which is in unvisited state and push it into
stack.mark the status of that node as visited.
3. Repeat steps 4 thru 6 until stack is empty.
4. POP a node N from stack and process it.
5. PUSH all the adjacent nodes of N which are in unvisited state into
stack.
6. Mark the status of those nodes to ‘visited’.
7. If the graph still contains nodes which are in ‘unvisited’ state then
goto step 2.
8. Return
 The step7 in the above procedure handle those nodes which does not
have a path from starting node to them. ( i.e. if the graph is an
unconnected graph).
 Stack data structure is used to implement DFS.
Algorithm for DFS:
DFS(input: Graph G)
{
Stack S; Integer x, t;
while (G has an unvisited node x)
{
visit(x); push(x,S);
while (S is not empty)
{
t := pop(S);
if (t has an unvisited neighbor y){ visit(y);
push(y,S); }
else pop(S);
}
}
}
/* Program for non-recursive implementation of DFS */
#include<stdio.h> void DFS(int v)
#define MAX 20 {
int Adj[MAX[[MAX],n,Stack[MAX], int i,x;
top=-1, visited[MAX]={0}; push(v);
void DFS(int); visted[v]=1;
void push(int); while(!stkempty())
int pop(); {
int stkempty() x=pop();
{ printf(“ %d”, x);
if(top==-1) for(i=;i<n;i++)
return 1; if(Adj[x][i]==1&&visited[i]==0)
else {
return 0; push(i);
} visited[i]=1;
main() }
{ }
int i,j; }
printf(“Enter the no. of vertices of void push(int v)
Graph”); {
scanf(“%d”,&n); Stack[++top]=x;
printf(“Enter the Adjacency Matrix:”); }
for(i=0;i<n;i++) int pop()
for(j=0;j<n;j++) {
scanf(“%d”,Adj[i][j]); int v;
printf(“\n The Depth First Traversal is:”); v=stack[top--];
for(i=0;i<n;i++) return v;
if(visited[i]==0) }
DFS(i);
}

Breadth First Search:


It is another graph traversal technique. It is also known as level order traversal.
The procedure for BFS is,
1. Select an unvisited node x, visit it, have it be the root in a BFS tree
being formed. Its level is called the current level.
2. From each node z in the current level, in the order in which the
level nodes were visited, visit all the unvisited neighbors of z. The
newly visited nodes from this level form a new level that becomes
the next current level.
3. Repeat step 2 until no more nodes can be visited.
4. If there are still unvisited nodes, repeat from Step 1.
The Breadth First Travesral of a graph is much similar to level by level traversal
of an ordered tree. BFS operates by processing nodes in layers. The BFS can
begin at any arbitrary node. The nodes which are adjacent to the start node are
processed first, and proceeds to adjacent nodes of the node that just visited. This
process continues until all the nodes are visited.
 Queue data structure is used to implement BFS.
Implementation procedure for BFS:
1. All nodes are initialized to ‘unvisited’ state and initialize queue to
empty.
2. Start with any node which is in unvisited state and insert it into queue.
Mark the status of that node as visited.
3. Repeat steps 4 thru 6 until queue is empty.
4. Delete a node N from queue and process it.
5. Insert all the adjacent nodes of N which are in unvisited state into
queue.
6. Mark the status of those nodes to ‘visited’.
7. If the graph still contains nodes which are in ‘unvisited’ state then goto
step 2.
8. Return
Algorithm for BFS:
BFS(input: graph G)
{
Queue Q; Integer x, z, y;
while (G has an unvisited node x)
{
visit(x); Enqueue(x,Q);
while (Q is not empty)
{
z := Dequeue(Q);
for all (unvisited neighbor y of z){
visit(y); Enqueue(y,Q); }
}
}
}
/* Program for non-recursive implementation of BFS */
#include<stdio.h> void BFS(int v)
#define MAX 20 {
int Adj[MAX[[MAX],n,Que[MAX], int i,x;
rear=-1, front=-1, visited[MAX]={0}; enque(v);
void BFS(int); visted[v]=1;
void enque(int); while(!queempty())
int deque(); {
int queempty() x=deque();
{ printf(“ %d”, x);
if(front==-1) for(i=0;i<n;i++)
return 1; if(Adj[x][i]==1&&visited[i]==0)
else {
return 0; enque(i);
} visited[i]=1;
main() }
{ }
int i,j; }
printf(“Enter the no. of vertices of void enque(int v)
Graph”); {
scanf(“%d”,&n); if(rear==-1)
printf(“Enter the Adjacency Matrix:”); front=0;
for(i=0;i<n;i++) que[++rear]=x;
for(j=0;j<n;j++) }
scanf(“%d”,Adj[i][j]); int deque()
printf(“\n The Breadth First Traversal {
is:”); int v=q[front];
for(i=0;i<n;i++) if(front==rear)
if(visited[i]==0) front=rear=-1;
BFS(i); else
} front++;
return v;
}

You might also like