DS图—图的连通分量
题目描述
输入无向图顶点信息和边信息,创建图的邻接矩阵存储结构,计算图的连通分量个数。
输入
测试次数t
每组测试数据格式如下:
第一行:顶点数 顶点信息
第二行:边数
第三行开始,每行一条边信息
输出
每组测试数据输出,顶点信息和邻接矩阵信息
输出图的连通分量个数,具体输出格式见样例。
每组输出直接用空行分隔。
样例输入
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
样例输出
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
基本思路
连通分量就是有多少个顶点相连可以构成一个图,所以只要用DFS就可以看看哪些顶点连通,哪些分开
#include <iostream>
#include <string>
using namespace std;
class Graph{
int vexNum;
int arcNum;
string *vex;
int **array;
bool *visit;
int count;
void DFS(int v);
int Index(string str);
public:
Graph();
~Graph();
void getConnect();
void outPut();
};
Graph::Graph():count(0) {
cin>>vexNum;
vex = new string[vexNum];
for(int i=0;i<vexNum;i++)
cin>>vex[i];
array = new int*[vexNum];
visit = new bool[vexNum];
for(int i=0;i<vexNum;i++)
{
visit[i] = false;
array[i] = new int[vexNum];
for(int j=0;j<vexNum;j++)
array[i][j] = 0;
}
cin>>arcNum;
for(int i=0;i<arcNum;i++)
{
string str1,str2;
cin>>str1>>str2;
int num1=Index(str1),num2=Index(str2);
array[num1][num2] = 1;
array[num2][num1] = 1;
}
}
Graph::~Graph() {
delete []visit;
delete []vex;
for(int i=0;i<vexNum;i++)
delete []array[i];
delete []array;
}
void Graph::DFS(int v) {
if(!visit[v])
{
visit[v] = true;
for(int j=0;j<vexNum;j++)
if(array[v][j]==1)
DFS(j);
}
}
void Graph::getConnect() {
for(int i=0;i<vexNum;i++)
if(!visit[i])
{
DFS(i);
count++;
}
}
int Graph::Index(string str) {
for(int i=0;i<vexNum;i++)
if(vex[i] == str)
return i;
return -1;
}
void Graph::outPut() {
for(int i=0;i<vexNum;i++)
if(i!=vexNum-1)
cout<<vex[i]<<' ';
else
cout<<vex[i]<<endl;
for(int i=0;i<vexNum;i++)
for(int j=0;j<vexNum;j++)
if(j!=vexNum-1)
cout<<array[i][j]<<' ';
else
cout<<array[i][j]<<endl;
cout<<count<<endl<<endl;
}
int main()
{
int t;
cin>>t;
while (t--)
{
Graph myGraph;
myGraph.getConnect();
myGraph.outPut();
}
return 0;
}
来源:CSDN
作者:~澄~
链接:https://blog.csdn.net/luoyeliufeng/article/details/103642133