Breadth First Search

1:  #include<stdio.h>  
2:  #include<conio.h>  
3:  void bfs(int v);  
4:  int adj[10][10],n;  
5:  void main()  
6:  {  
7:       int i,j,v=1;  
8:       clrscr();  
9:       printf("BREADTH FIRST SEARCH\n\n");  
10:       printf("\nEnter the number of nodes");  
11:       scanf("%d",&n);  
12:       printf("Enter the adjacency matrix");  
13:       for(i=1;i<=n;i++)  
14:       {  
15:            for(j=1;j<=n;j++)  
16:                 scanf("%d",&adj[i][j]);  
17:       }  
18:       printf("\nthe visited nodes are:");  
19:       printf("%d",v);  
20:       bfs(v);  
21:       getch();  
22:  }  
23:  void bfs(int v)  
24:  {  
25:       int u,w ,q[10],i,vis[10],front=0,rear=0;  
26:       for(i=1;i<=n;i++)  
27:            vis[i]=0;  
28:       vis[v]=1;  
29:       u=v;  
30:       while(v<=n)  
31:       {  
32:            front=0;  
33:            rear=0;  
34:            for(i=1;i<=n;i++)  
35:                 q[i]=0;  
36:            for(w=1;w<=n;w++)  
37:            {  
38:                 if(adj[v][w]==1)  
39:                  {  
40:                       if(vis[w]==0)  
41:                       {  
42:                             front=front+1;  
43:                             q[front]=w;  
44:                             vis[w]=1;  
45:                       }  
46:                  }  
47:             }  
48:             if(rear==0&&front==0)  
49:                  return;  
50:            else  
51:             {  
52:                  while(rear<front)  
53:                      {  
54:                       rear=rear+1;  
55:                       u=q[rear];  
56:                       printf("%d",u);  
57:                  }  
58:             }  
59:            v++;  
60:        }  
61:  }  

No comments:

Post a Comment

Code Of The day - Suggest An Output For The Snippet

  #include<stdio.h>   
  int main()   
  {   
   float a=3.15529;   
   printf("%2.1f\n", a);   
   return 0;   
  }   
· A Code Archive - code1archive