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