#include <stdio.h>
#include <stdlib.h>
#define MAX 10
struct node
{
int data;
struct node *link;
};
void buildadjm(int adj[][MAX], int n)
{
int i,j;
printf("enter adjacency matrix \n",i,j);
for(i=0;i<n;i++)
for(j=0;j<n;j++)
scanf("%d",&adj[i][j]);
}
/* A function to insert a new node in queue*/
struct node *addqueue(struct node *p,int val)
{
struct node *temp;
if(p == NULL)
{
p = (struct node *) malloc(sizeof(struct node)); /* insert the new node first node*/
if(p == NULL)
{
printf("Cannot allocate\n");
exit(0);
}
p->data = val;
p->link=NULL;
}
else
{
temp= p;
while(temp->link != NULL)
{
temp = temp->link;
}
temp->link = (struct node*)malloc(sizeof(struct node));
temp = temp->link;
if(temp == NULL)
{
printf("Cannot allocate\n");
exit(0);
}
temp->data = val;
temp->link = NULL;
}
return(p);
}
struct node *deleteq(struct node *p,int *val)
{ struct node *temp;
if(p == NULL)
{
printf("queue is empty\n");
return(NULL);
}
*val = p->data;
temp = p;
p = p->link;
free(temp);
return(p);
}
void bfs(int adj[][MAX], int x,int visited[], int n, struct node **p)
{
int y,j,k;
*p = addqueue(*p,x);
do{
*p = deleteq(*p,&y);
if(visited[y] == 0)
{
printf("\nnode visited = %d\t",y);
visited[y] = 1;
for(j=0;j<n;j++)
if((adj[y][j] ==1) && (visited[j] == 0))
*p = addqueue(*p,j);
}
}while((*p) != NULL);
}
void main()
{
int adj[MAX][MAX];
int n;
struct node *start=NULL;
int i, visited[MAX];
printf("enter the number of nodes in graph maximum = %d\n",MAX);
scanf("%d",&n);
buildadjm(adj,n);
for(i=0; i<n; i++)
visited[i] =0;
for(i=0; i<n; i++)
if(visited[i] ==0)
bfs(adj,i,visited,n,&start);
}
Wednesday, July 20, 2011
BREADTH-FIRST TRAVERSAL
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment