给定一个有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 }
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#define MaxVertexNum 10
typedef struct GNode* PtrToGNode;
struct GNode {
int Nv;
int Ne;
int G[MaxVertexNum][MaxVertexNum];
};
typedef PtrToGNode MGraph;
int Visited[MaxVertexNum];
MGraph CreateGraph(int VertexNum) {
int v, w;
MGraph Graph;
Graph = (MGraph)malloc(sizeof(struct GNode));
Graph->Nv = VertexNum;
Graph->Ne = 0;
for (v = 0; v < Graph->Nv; v++) {
Visited[v] = 0;
for (w = 0; w < Graph->Nv; w++)
Graph->G[v][w] = 0;
}
return Graph;
}
void InsertEdge(MGraph Graph, int v1, int v2) {
Graph->G[v1][v2] = 1;
Graph->G[v2][v1] = 1;
}
void Visit(int v) {
printf(" %d",v);
}
void DFS(MGraph Graph,int V) {
if (!Visited[V]) {
Visit(V);
Visited[V] = 1;
int i;
for (i = 0; i < Graph->Nv; i++) {
if (Graph->G[V][i] && !Visited[i]) {
DFS(Graph,i);
}
}
}
}
void BFS(MGraph Graph, int V) {
if (!Visited[V]) {
int Queue[MaxVertexNum];
int v, w;
int front = 0,rear = 0;
Visit(V);
Visited[V] = 1;
Queue[++rear] = V;
while (rear != front) {
v = Queue[++front];
for (w = 0; w < Graph->Nv; w++) {
if (!Visited[w] && Graph->G[v][w]) {
Visit(w);
Visited[w] = 1;
Queue[++rear] = w;
}
}
}
}
}
int main() {
MGraph Graph;
int v1,v2;
int Nv, i;
scanf("%d", &Nv);
Graph = CreateGraph(Nv);
scanf("%d",&(Graph->Ne));
if (Graph->Ne != 0) {
for (i = 0; i < Graph->Ne; i++) {
scanf("%d%d", &v1, &v2);
InsertEdge(Graph, v1, v2);
}
}
for (i = 0; i < Graph->Nv; i++) {
if (!Visited[i]) {
printf("{");
DFS(Graph, i);
printf("}\n");
}
}
for (i = 0; i < Graph->Nv; i++)
Visited[i] = 0;
for (i = 0; i < Graph->Nv; i++) {
if (!Visited[i]) {
printf("{");
BFS(Graph, i);
printf("}\n");
}
}
return 0;
}