题目描述
输入无向图顶点信息和边信息,创建图的邻接矩阵存储结构,计算图的连通分量个数。
输入
测试次数t
每组测试数据格式如下:
第一行:顶点数 顶点信息
第二行:边数
第三行开始,每行一条边信息
输出
每组测试数据输出,顶点信息和邻接矩阵信息
输出图的连通分量个数,具体输出格式见样例。
每组输出直接用空行分隔。
输入样例1
3
4 A B C D
2
A B
A C
6 V1 V2 V3 V4 V5 V6
5
V1 V2
V1 V3
V2 V4
V5 V6
V3 V5
8 1 2 3 4 5 6 7 8
5
1 2
1 3
5 6
5 7
4 8
输出样例1
A B C D
0 1 1 0
1 0 0 0
1 0 0 0
0 0 0 0
2
V1 V2 V3 V4 V5 V6
0 1 1 0 0 0
1 0 0 1 0 0
1 0 0 0 1 0
0 1 0 0 0 0
0 0 1 0 0 1
0 0 0 0 1 0
1
1 2 3 4 5 6 7 8
0 1 1 0 0 0 0 0
1 0 0 0 0 0 0 0
1 0 0 0 0 0 0 0
0 0 0 0 0 0 0 1
0 0 0 0 0 1 1 0
0 0 0 0 1 0 0 0
0 0 0 0 1 0 0 0
0 0 0 1 0 0 0 0
3
NOTICE:计算图的连通分量个数,思路很简单,写一个BFS或者DFS都行,然后开始遍历每个顶点,只要这个顶点未被访问过(flag=0),就以这个顶点为起点遍历图,计数器加一;最终计数器就是连通分量个数。
#include <iostream>
using namespace std;
class Graph
{
private:
string* data;
int** Matrix;
int vertexnum;
int edgenum;
int* flag;
int cc = 1;//connected component连通分量
int find(string s)//根据顶点信息返回该顶点下标
{
for (int i = 0; i < vertexnum; i++)
{
if (s == data[i])
return i;
}
}
public:
Graph()
{
cin >> vertexnum;
data = new string[vertexnum];
for (int i = 0; i < vertexnum; i++)
cin >> data[i];
Matrix = new int* [vertexnum];
for (int i = 0; i < vertexnum; i++)
Matrix[i] = new int[vertexnum];
for (int i = 0; i < vertexnum; i++)
for (int j = 0; j < vertexnum; j++)
Matrix[i][j] = 0;
flag = new int[vertexnum];
for (int i = 0; i < vertexnum; i++)
flag[i] = 0;
cin >> edgenum;
string s1, s2;
for (int i = 0; i < edgenum; i++)
{
cin >> s1 >> s2;
Matrix[find(s1)][find(s2)] = 1;
Matrix[find(s2)][find(s1)] = 1;
}
}
~Graph()
{
delete[]data;
for (int i = 0; i < vertexnum; i++)
delete[]Matrix[i];
delete[]Matrix;
}
void BFS(int index)
{
flag[index] = 1;
for (int i = 0; i < vertexnum; i++)
if (Matrix[index][i] && !flag[i])
BFS(i);
}
void BFS()
{
BFS(0);
for (int i = 0; i < vertexnum; i++)
if (flag[i] == 0)
{
cc++;
BFS(i);
}
}
void display()
{
for (int i = 0; i < vertexnum; i++)
{
cout << data[i];
if (i == vertexnum - 1)
cout << endl;
else
cout << " ";
}
for (int i = 0; i < vertexnum; i++)
for (int j = 0; j < vertexnum; j++)
{
cout << Matrix[i][j];
if (j == vertexnum - 1)
cout << endl;
else
cout << " ";
}
cout << cc << endl;
cout << endl;
}
};
int main()
{
int t;
cin >> t;
while (t--)
{
Graph g;
g.BFS();
g.display();
}
return 0;
}