0
点赞
收藏
分享

微信扫一扫

链式向前星 BFS

#include<stdio.h> 

 #include<stdlib.h> 

 #include<string.h> 

 #include<math.h> 

 #include<queue> 

 #include<iostream> 

 #include<algorithm> 

 using namespace std; 



 const int sizen=1000; 

 int head[sizen]; 

 bool mark[sizen]; 

 struct ele 

 { 

     int to; 

     int w; 

     int next; 

 }p[sizen]; 

 int e,V,E; 



 void add(int x,int y,int z) 

 { 

     p[e].to=y; 

     p[e].w=z; 

     p[e].next=head[x]; 

     head[x]=e++; 

 } 



 void BFS(int x,int n) 

 { 

     queue<int>pp; 

     int t,i; 

     printf("%d\n",x); 

     mark[x]=true; 

     pp.push(x); 

     while(pp.size()) 

     { 

         t=pp.front(); 

         pp.pop(); 

         for(i=head[t];i!=-1;i=p[i].next) 

             if(!mark[p[i].to]) 

             { 

                 printf("%d\n",p[i].to); 

                 pp.push(p[i].to); 

                 mark[p[i].to]=true; 

             } 

     } 

 } 



 int main() 

 { 

     int x,y,z; 

     int i; 

     while(scanf("%d%d",&V,&E)!=EOF) 

     { 

         memset(head,-1,sizeof(head)); 

         memset(mark,false,sizeof(mark)); 

         while(E--) 

         { 

             scanf("%d%d%d",&x,&y,&z); 

             add(x,y,z); 

             add(y,x,z); 

         } 

         for(i=1;i<=V;i++) 

             if(!mark[i]) 

                 BFS(i,V); 

     } 

     return 0; 

 }

举报

相关推荐

0 条评论