题目描述
给定一个有N个顶点和E条边的无向图,请用DFS和BFS分别列出其所有的连通集。假设顶点从0到N−1编号。进行搜索时,假设我们总是从编号最小的顶点出发,按编号递增的顺序访问邻接点。
输入格式:
输入第1行给出2个整数N(0<N≤10)和E,分别是图的顶点数和边数。随后E行,每行给出一条边的两个端点。每行中的数字之间用1空格分隔。
输出格式:
按照{v1, v2, … ,vk}的格式,每行输出一个连通集。先输出DFS的结果,再输出BFS的结果。
输入样例:
8 6
0 7
0 1
2 0
4 1
2 4
3 5
输出样例:
{ 0 1 4 2 7 }
{ 3 5 }
{ 6 }
{ 0 1 2 7 4 }
{ 3 5 }
{ 6 }
代码
#include<stdio.h>
#include<malloc.h>
#define MaxVertexNum 11
#define INFINITY 65535
int Visited[MaxVertexNum] = {0};/*标记节点是否访问过*/
int Visited1[MaxVertexNum] = {0};/*标记节点是否访问过,由于上一个数组已经被DFS改变了,直接再设一个让BFS使用*/
typedef int WeightType;
typedef struct GMnode *PtrToGnode;
struct GMnode{/*用邻接矩阵表示图*/
int Nv; /*顶点数*/
int Ne; /*边数*/
WeightType G[MaxVertexNum][MaxVertexNum];
};
typedef PtrToGnode MGraph;
typedef int Vertex;
MGraph CreateGraph(int VertexNum)
{/*初始化一个有VerTexNum个顶点但没有边的图*/
Vertex V, W;
MGraph Graph;
Graph = (MGraph)malloc(sizeof(struct GMnode));
Graph->Nv = VertexNum;
Graph->Ne = 0;
for(V=0;V<Graph->Nv;V++)
for(W=0;W<Graph->Nv;W++)
Graph->G[V][W] = 0;
return Graph;
}
typedef struct EMnode *PtrToEnode;
struct EMnode{
Vertex V1, V2;
// WeightType Weight;
};
typedef PtrToEnode MEdge;
void InsertMEdge(MGraph Graph, MEdge E)
{/*插入边*/
Graph->G[E->V1][E->V2] = 1;
Graph->G[E->V2][E->V1] = 1;
}
MGraph BuildGraph()
{/*建立图*/
MGraph Graph;
int i;
Vertex v;
scanf("%d",&v);
Graph = CreateGraph(v);
scanf("%d",&Graph->Ne);
MEdge E = (MEdge)malloc(sizeof(struct EMnode));
for(i=0;i!=Graph->Ne;i++)
{
scanf("\n%d %d",&E->V1,&E->V2);
InsertMEdge(Graph, E);
}
return Graph;
}
void DFS(MGraph Graph, Vertex V)
{/*深度优先遍历*/
printf("%d ",V);
Visited[V] = 1;
Vertex i;
for(i=0;i!=Graph->Nv;++i)
if( !Visited[i] && Graph->G[V][i] )
DFS(Graph, i);
}
Vertex Que[MaxVertexNum] = {-1};
int min = 0;
int max = -1;
void Enqueue(Vertex V)
{/*入队操作*/
Que[++max] = V;
}
Vertex Dequeue()
{/*出队操作*/
return Que[min++];
}
void BFS(MGraph Graph, Vertex V)
{/*广度优先遍历*/
Vertex i;
printf("%d ",V);
Visited1[V] = 1;
Enqueue(V);
while(min<=max){
V = Dequeue();
for(i=0;i!=Graph->Nv;++i){
if( !Visited1[i] && Graph->G[V][i] ){
Visited1[i] = 1;
Enqueue(i);
printf("%d ",i);
}
}
}
}
void ListComponents(MGraph G)
{/*遍历不同的连通集*/
Vertex i;
for(i=0;i!=G->Nv;++i)
if(!Visited[i]){
printf("{ ");
DFS(G, i);
printf("}\n");
}
for(i=0;i!=G->Nv;++i)
if(!Visited1[i]){
printf("{ ");
BFS(G, i);
printf("}\n");
}
}
int main()
{
MGraph Graph = BuildGraph();
ListComponents(Graph);
return 0;
}