BFS 遍历图
1 #include<iostream> 2 #include<cstdio> 3 using namespace std; 4 int que[10000]; 5 int vis[10000]; 6 int map[1000][1000]; 7 int n,m; 8 void bfs(int u) 9 { 10 cout<<char(u+65)<<" "; 11 int head=0; 12 int tail=1; 13 que[tail]=u; 14 vis[u]=1; 15 while(head<tail) 16 { 17 head++; 18 int k=que[head]; 19 for(int i=1;i<=n;i++) 20 { 21 if(map[k][i]==1&&vis[i]==0) 22 { 23 tail++; 24 que[tail]=i; 25 cout<<char(i+65)<<" "; 26 vis[i]=1; 27 } 28 } 29 } 30 } 31 int main() 32 { 33 cin>>n>>m; 34 char x,y; 35 for(int i=1;i<=m;i++) 36 { 37 cin>>x>>y; 38 map[x-64-1][y-64-1]=1; 39 map[y-64-1][x-64-1]=1; 40 } 41 bfs(0); 42 return 0; 43 }