MODULE 5 Graphs
MODULE 5 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)
#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);