求连通分量(无向图,邻接矩阵,BFS)

1、题目:


 Problem Description

设有一无向图,其顶点值为字符型并假设各值互不相等,采用邻接矩阵表示法存储表示。利BFS用算法求其各连通分量,并输出各连通分量中的顶点。

 Input

有多组测试数据,每组数据的第一行为两个整数n和e,表示n个顶点和e条边(0

 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

hwt


2、参考代码:


#include 
#include 
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>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<>n>>e){
		if(flag)
			cout<>a;
		MGraph w(a,n,e);
		memset(w.vis,0,sizeof(w.vis));
		int x=1;
		for(int i=0;i



你可能感兴趣的:(数据结构)