1、題目:
Problem Description
Input
Output
Sample Input
4 4 ABCD 0 1 0 3 1 2 1 3 4 3 ABCD 0 1 0 3 1 3
Sample Output
1:A,B,D,C 1:A,B,D 2:C
Author
2、參考代碼:
#include <iostream>
#include <string.h>
using namespace std;
class MGraph{
private:
int vertexNum,arcNum;
char vertex[111];
int edge[111][111];
public:
int vis[111];
MGraph(char* a,int n,int e);
~MGraph(){}
void BFS(int v);
};
MGraph::MGraph(char* a,int n,int e){
vertexNum=n;
arcNum=e;
memset(edge,0,sizeof(edge));
int i,j;
for(i=0;i<n;i++)
vertex[i]=a[i];
while(e--){
cin>>i>>j;
edge[i][j]=edge[j][i]=1;
}
}
void MGraph::BFS(int v){
int front,rear,count=0;
front=rear=-1;
int Q[111];
vis[v]=1;
Q[++rear]=v;
cout<<vertex[v];
while(front!=rear){
v=Q[++front];
for(int j=0;j<vertexNum;j++){
if(edge[v][j]==1 && !vis[j]){
cout<<","<<vertex[j];
vis[j]=1;
Q[++rear]=j;
}
}
}
}
int main()
{
int n,e;
bool flag=false;
char a[111];
while(cin>>n>>e){
if(flag)
cout<<endl;
cin>>a;
MGraph w(a,n,e);
memset(w.vis,0,sizeof(w.vis));
int x=1;
for(int i=0;i<n;i++){
if(w.vis[i]==0){
cout<<x++<<":";
w.BFS(i);
cout<<endl;
}
}
flag=true;
}
return 0;
}