给定一个有N个顶点和E条边的无向图,请用DFS和BFS分别列出其所有的连通集。假设顶点从0到N−1编号。进行搜索时,假设我们总是从编号最小的顶点出发,按编号递增的顺序访问邻接点。
输入格式:
输入第1行给出2个整数N(0<N≤10)和E,分别是图的顶点数和边数。随后E行,每行给出一条边的两个端点。每行中的数字之间用1空格分隔。
输出格式:
按照"{ v 1 v 2... v k { v_1 v_2... v_k} v1v2...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 }
思路
由于整数N(0<N≤10),维度不大,可以采用邻接矩阵建立图,相关操作见书本。
关于深度优先搜索(DFS),类似于数的先序遍历。其中定义了全局变量Visited1[]用来记录该方法节点的访问情况。
关于广度优先搜索(BFS),类似于数的层次遍历,采用队列的思想。其中全局变量Visited2[]用来记录该方法节点的访问情况。
编译器 C(gcc)
#include<stdio.h>
#include<stdlib.h>
typedef int Vertex;
typedef int DataType;
typedef struct GNode *PtrToGNode;
typedef int WeightType;
struct GNode
{
int Nv;
int Ne;
WeightType G[10][10];
//DataType Data[10];
};
typedef PtrToGNode MGraph;
typedef struct ENode *PtrToENode;
struct ENode
{
Vertex V1,V2;
//WeightType Weight;
};
typedef PtrToENode Edge;
MGraph CreatGraph(int VertexNum)
{
Vertex V,W;
MGraph Graph;
Graph=(MGraph)malloc(sizeof(struct GNode));
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;
}
void InsertEdge(MGraph Graph,Edge E)
{
Graph->G[E->V1][E->V2]=1;
Graph->G[E->V2][E->V1]=1;
}
MGraph BuildGraph()
{
MGraph Graph;
Edge E;
int Nv,i;
scanf("%d",&Nv);
Graph=CreatGraph(Nv);
scanf("%d",&(Graph->Ne));
if(Graph->Ne!=0)
{
E=(Edge)malloc(sizeof(struct ENode));
for(i=0;i<Graph->Ne;i++)
{
scanf("%d %d",&E->V1,&E->V2);
InsertEdge(Graph,E);
}
}
return Graph;
}
int Visited1[10]={0};
void DFS(MGraph Graph,Vertex V)
{
Vertex W;
// MGraph Graph;
Visited1[V]=1;
printf("%d ",V);
//int i=0;
for(W=0;W<Graph->Nv;W++)
{
if(Graph->G[V][W]==1&&Visited1[W]==0)
DFS(Graph,W);
}
}
//int Q[10]={0};
typedef struct Queue *PtrToQueue;
struct Queue
{
int Q[10];
int Head;
int Rear;
};
typedef PtrToQueue MQ;
void CreateQueue(MQ Q1)
{
for(int i=0;i<10;i++)
Q1->Q[i]=0;
Q1->Head=-1;
Q1->Rear=-1;
}
void Enqueue(Vertex V,MQ Q1)
{
Q1->Rear=Q1->Rear+1;
Q1->Q[Q1->Rear]=V;
}
int Dequeue(MQ Q1)
{
int T;
T=(Q1->Head)+1;
(Q1->Head)++;
return Q1->Q[T];
}
int Visited2[10]={0};
void BFS(MGraph Graph,Vertex V,MQ Q1)
{
Vertex W;
Visited2[V]=1;
//printf("%d",V);
Enqueue(V,Q1);
while(Q1->Head!=Q1->Rear)
{
V=Dequeue(Q1);
printf("%d ",V);
for(W=0;W<Graph->Nv;W++)
{
if(Graph->G[V][W]==1&&Visited2[W]==0)
{
Visited2[W]=1;
Enqueue(W,Q1);
//printf("%d",W);
}
}
}
}
void ListComponents(MGraph Graph,MQ Q)
{
//Queue Q;
//CreatQueue(Q);
int V;
for(V=0;V<Graph->Nv;V++)
{
if(Visited1[V]==0)
{
printf("{ ");
DFS(Graph,V);
printf("}");
printf("\n");
}
}
for(V=0;V<Graph->Nv;V++)
{
if(Visited2[V]==0)
{
printf("{ ");
BFS(Graph,V,Q);
printf("}");
printf("\n");
}
}
}
int main()
{
MQ Q;
Q=(MQ)malloc(sizeof(struct Queue));
CreateQueue(Q);
MGraph G;
G=BuildGraph();
ListComponents(G,Q);
system("pause");
return 0;
}