0
点赞
收藏
分享

微信扫一扫

邻接矩阵 BFS

boomwu 2023-08-23 阅读 41

#include<stdio.h> 

 #include<queue> 

 #include<stdlib.h> 

 #include<string.h> 

 #include<math.h> 

 #include<iostream> 

 #include<algorithm> 

 using namespace std; 



 const int sizen=10000; 

 int Map[sizen][sizen]; 

 bool mark[sizen]; 



 void BFS(int x,int n) 

 { 

     int i; 

     int t; 

     queue<int>p; 

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

     mark[x]=true; 

     p.push(x); 

     while(p.size()) 

     { 

         t=p.front(); 

         p.pop(); 

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

             if(!mark[i]&&Map[t][i]) 

             { 

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

                 mark[i]=true; 

                 p.push(i); 

             } 

     } 

 } 



 int main() 

 { 

     int V,E; 

     int x,y; 

     int i; 

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

     { 

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

         memset(Map,0,sizeof(Map)); 

         while(E--) 

         { 

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

             Map[x][y]=Map[y][x]=1; 

         } 

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

             if(!mark[i]) 

                 BFS(i,V); 

     } 

     return 0; 

 }

举报

相关推荐

0 条评论