0% found this document useful (0 votes)
68 views29 pages

MODULE 5 Graphs

The document discusses graphs and graph algorithms. It defines graph terminology like vertices, edges, directed/undirected graphs. It describes representations of graphs using adjacency matrices and lists. It explains traversal algorithms for graphs - breadth first search (BFS) and depth first search (DFS). BFS visits all neighbors of a node before moving to the next level, while DFS fully explores each branch before backtracking.

Uploaded by

Ral Ralte
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)
68 views29 pages

MODULE 5 Graphs

The document discusses graphs and graph algorithms. It defines graph terminology like vertices, edges, directed/undirected graphs. It describes representations of graphs using adjacency matrices and lists. It explains traversal algorithms for graphs - breadth first search (BFS) and depth first search (DFS). BFS visits all neighbors of a node before moving to the next level, while DFS fully explores each branch before backtracking.

Uploaded by

Ral Ralte
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/ 29

GRAPHS

Graphs
➢Definitions
➢Terminologies
➢Matrix and adjacency list representation of
graphs
➢Elementary graph operations
➢Traversal methods:
➢Breadth First Search(BFS)
➢Depth First Search(DFS)
Terminologies
▪ Vertex(node): A vertex/ node normally is
represented by a circle.
Vertex Set, V={ 1,2,3}
▪ Edge: If u and v are two vertices, a line joining
2 vertices is called an edge.
➢Undirected edge( An edge with no direction)
Eg: (1,6) 1 and 6 end points of the edge.
➢Directed edge(An edge with direction)
Eg: <1,6> 1 represents tail of the edge, 6 Is head of
the edge.
▪ Graph: A graph G is defined as a pair of two sets
V and E denoted by G=(V,E)

▪ Directed Graph/Digraph: A graph G=(V,E) in


which every edge is directed.

▪ Undirected Graph: A graph G=(V,E) in which


every edge is undirected.

▪ Self-loop/self-edge: A loop is an edge which


starts and ends on the same vertex.
A loop is represent by an ordered pair (i,i)
▪ Multigraph: A graph with multiple occurrence
of the same edge b/w any two vertices is called
multigraph.
▪ Complete graph: A graph G=(V,E) is said to be a
complete, if there exists an edge b/w every pair
of vertices.
▪ Path: Let G=(V,E) be a graph. A path from vertex
u to vertex v in an undirected/directed graph is
a sequence of adjacent vertices (u, v0,v1,
v2…vk,v) such that: (u,v0), (v0, v1), …(vk,v) are
edges in G.
▪ Simple path: A simple path is a path in which all
vertices except possibly the first and last are
distinct.

▪ Length of the path: Number of edges in the path.

▪ Cycle/Circuit: A cycle is a path in which the first and


last vertices are same.

▪ Cyclic graph: A graph with at least one cycle.

▪ Acyclic graph: A graph with at least no cycle.


Connected graph: A graph G(directed or
undirected) is said to be connected if and only if
there exists a path b/w every pair of vertices.

Disconnected graph: Let G=(V,E) be a graph. If there


exists at least one vertex in a graph that cannot
be reached from other vertices in the graph, then
such a graph is called disconnected graph.
Representation of graph
➢Adjacency matrix
➢Adjacency linked list

Adjacency matrix: Let G=(V,E) be a graph where V


is set of vertices and E is set of edges. Let N be
the number of vertices in graph G. The adjacency
matrix A of a graph G is formally defined as
shown below:
A[i][j]=1 if there is an edge from vertex i to j
A[i][j]=0 if there is no edge from vertex i to j
Adjacency linked list: Let G=(V,E) be a graph. An
adjacency linked list is an array of n linked lists
where n is the number of vertices in graph G.
Each location of the array represents a vertex
of the graph. For each vertex u € V, a linked list
consisting of all the vertices adjacent to u is
created and stored in A[u]. The resulting array
A is an adjacency list.
Weighted graphs: A graph in which a number is
assigned to each edge in a graph is called weighted
graph. These numbers are called costs or weights.

Representation of weighted graph:


➢ Adjacency matrix
➢ Adjacency linked list

Cost adjacency matrix: Let G=(V,E) be the graph where V is


set of vertices and E is set of edges with n number of
vertices. The cost adjacency matrix A of a graph G is
formally defined as:
A[i][j]= w , if there is a weight associated with edge from
vertex i to j
A[i][j]= infinity, if there is no edge from vertex i to j
For undirected graph,
A[i][j]= w , if there is a weight associated with edge
(I,j) or(j,i)
A[i][j]= infinity, if there is no edge from vertex i to
vertex j.
Cost adjacency linked list: Let G=(V,E) be the graph
where V is set of vertices and E is set of edges with n
number of vertices. A cost adjacency linked list is an array
of n linked lists. For each vertex u € V, A[u] contains the
address of a linked list. All the vertices which are adjacent
from vertex u are stored in the form of a linked list( in an
arbitrary manner) and the starting address of first node is
stored in A[u]. If I,j and k are the vertices adjacent to the
vertex u, then I,j and k are stored in a linked list along with
the weights in A[u].
// Function to read adjacency matrix
Void read_AM( int a[5][5], int n)
{
int I,j;
//read n value
for( i=0; i<n; i++)
{
for (j=0; j<n; j++)
{
scanf(“%d”, &a[i][j]);
}
}
}
//Function to read adjacency list
Void read_AL( NODE a[], int n)
{
int I,j,m,item;
//read n value
for( i=0; i<n; i++)
{
printf(“Enter the num of nodes adjacent to %d:”, i);
scanf(“%d”, &m);
if(m==0) continue;
printf(“Enter nodes adjacent to %d:”,i);
for(j=0; j<m; j++)
{
scanf(“%d”,&item);
a[i]=insert_rear(item, a[i]);
}
}
}
Graph Traversals
Definition: The process of visiting each node of
a graph systematically in some order is called
graph traversal.
Two techniques:
➢Breadth First Search (BFS)
➢Depth First Search (DFS)
Depth First Search(DFS)
Def: In DFS, a vertex u is picked as source vertex and
is visited.
The vertex u at this point is said to be unexplored.
The exploration of the vertex u is postponed and a
vertex v adjacent to u is picked & is visited.
Now, the search begins at the vertex v.
There may be still some nodes which are adjacent
to u but not visited.
When the vertex v is completely examined, then
only u is examined. The search will terminate when
all the vertices have been examined.
Design methodology
Step1: select node u as the start vertex, push u onto stack & make it as visited.
We add u to S for marking.
Step2: while stack is not empty
For vertex u on top of stack, find the next immediate adjacent
vertex.
If v is adjacent
If a vertex v not visited then
push it on to stack & no. it in the order it is
pushed.
mark it as visited by adding v to S
else
ignore the vertex
endif
else
remove the vertex from the stack
number it in the order it is popped.
endif
end while
Step3: Repeat step 1and step2 untill alll the vertices in the graph are considered.
DFS using adjacency matrix

#include<stdio.h>
Int a[10][10], s[10],n;
Void main()
{
int i, source;
printf(“Enter the number of nodes in the graph:”);
scanf(“%d”,&n);
printf(Enter the adjacency matrix:”);
read_AM(a,n);
for(source=0; source<n; source++)
{
for(i=0; i<n; i++)
s[i]=0;
printf(“The nodes reachable from %d”, source);
dfs(source);
}
}
Void dfs(int u)
{
int v;
s[u]=1;
printf(“%d”,u);
for(v=0; v<n; v++)
{
if(a[u][v]==1 && s[v]==0)
dfs(v);
}
}
//DFS traversal using adjacency list
Struct node
{
int info;
struct node * link;
};
Typedef struct node *NODE;
NODE a[10];
Int s[10],n;
//include getnode function, function to insert an
elem itno Q(insert_rear function), read adjacency
matrix, DFS
//include main function
Void dfs(int u)
{
int v;
NODE temp;
s[u]=1;
printf(“%d”,u);
for(temp=a[u]; temp!=NULL; temp=temp->link)
{
if(s[temp->info]==0)
{
dfs(temp->info);
}
}
}
Breadth First Search(BFS):
Def: The BFS is a method of traversing the graph
from an arbitrary vertex say u.
First, visit the node u. Then we visit all
neighbors of u.
Then we visit the neighbors of neighbors of u
and so on.
That is, we visit all the neighboring nodes first
before moving to next level neighbors.
The search will terminate when all the vertices
have been visited.
Initialization: Take any initial node u and make that
node as visited by inserting that node in to
Queue.
Steps:
1. Delete an element from Queue
2. Find the nodes adjacent to element[ which is
deleted from Queue] but not in S[contains the
list of visited nodes]
3. Add adjacent nodes to S & also insert into
Queue
Repeat the above 3 steps until Queue becomes
empty.
//Program to traverse the graph using BFS
void main()
{
int n,a[10][10], source, i,j;
clrscr();
printf("Enter the number of nodes:");
scanf("%d",&n);
printf("Enter the adjacency matrix:\n");
for(i=0; i<n; i++)
{
for(j=0; j<n; j++)
{
scanf("%d", &a[i][j]);
}
}
for(source=0; source<n; source++)
{
bfs(a,n,source);
}
getch();
}
void bfs(int a[10][10], int n, int u)
{
int f,r,q[10],v;
int s[10]={0}; //initialize all elem in s to 0, no node visited
printf("The nodes visited from %d:",u);

f=0, r=-1; // Q empty


q[++r]=u; // Insert u into Q
s[u]=1; // Insert u to s
printf("%d",u); //print node visited
while(f<=r)
{
u=q[f++]; //del an elem from Q
for(v=0; v<n; v++)
{
if(a[u][v]==1) //If v is adjacent to u
{
if(s[v]==0) // If v is not in S i.e, V has not been visited
{
printf("%d",v); // print the node visited

s[v]=1; //add v to s, mark as visited


q[++r]=v; //insert v into Q
}
}
}
}
printf("\n");
}
//BFS traversal using adjacency list
void main()
{
int n, source, i;
NODE a[10];
clrscr();
printf("Enter the number of nodes:");
scanf("%d",&n);
printf("Enter the adjacency matrix:\n");
for(i=0; i<n; i++)
{
a[i]=NULL;
}
read_AL(a,n);
for(source=0; source<n; source++)
{
bfs(a,n,source);
}
getch();
}
// Insert an item at the rear end of the list

NODE insert_rear ( int item, NODE first)


{
NODE temp, cur;
-------------------------------------------------------------------------------------------------------
temp = getnode();
temp->info = item;
temp->link = NULL;
---------------------------------------------------------------------------------------------------------
if (first == NULL) return temp;
--------------------------------------------------------------------------------------------------------
cur = first;
while (cur->link != NULL)
{
cur = cur->link;
}
-----------------------------------------------------------------------------------------------------------
cur->link = temp;
------------------------------------------------------------------------------------------------------------
return first;
}
// delete a node from front end
NODE delete_front(NODE first)
{
NODE temp;
If(first==NULL)
{
return NULL;
}
Temp=first;
Temp=temp->link;
Free(first);
Return temp;
}
Void bfs(NODE a[], int n, int u)
{
NODE q,list;
Int v;
Int s[10]={0}; //NO node is visited
Printf(“The node visited from %d:”,u);
q=NULL; // queue is empty
q=insert_rear(u,q); //insert u into queue
s[u]=1;
printf(“%d”,u); //print the node visited
while(q!=NULL)
{
u=q->info //delete a node from queue
q=delete_front(q);
list=a[u]; //obtain nodes adjacent to u
while(lis!=NULL) //as long as adjacent nodes exist
{
v=list->info; //v is the node adjacent to u
if(s[v]==0) //if v is not in S i.e, v has not been visited
{
Printf(“%d”,v); //print the node visited
S[v]=1; //add v to s, mark it as visited
q=insert_rear(v,q);
}
List=list->link;
}
}
Printf(“\n”);
}

You might also like