给定一个有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<stdlib.h> typedef struct node { int y; }Node; typedef struct line { int end; int top; Node a[10]; }Line,*qLine; typedef struct stack { int top; Node a[10]; }Stack, *qStack; Node Pop(qStack s) { Node n; n = s->a[s->top]; s->top--; return n; } void Push(qStack s,Node n) { s->top++; s->a[s->top] = n; } //遍历 void LookAll(int a[][10],qStack s,int *b,int numbers) { int start = 0, flag = 0, count = 0; while (count!=numbers) { for (int i = 0; i < numbers; i++) { if (b[i] == 0) { start = i; break; } } Node N, n; N.y = start; Push(s, N); printf("{"); printf(" %d", N.y); b[N.y] = 1; count++; while (s->top != -1) { flag = 0; n.y = s->a[s->top].y; for (int i = 0; i < numbers; i++) { if (a[n.y][i] == 1&& b[i] != 1) { start = i; N.y = start; Push(s, N); printf(" %d", N.y); b[N.y] = 1; count++; flag = 1; break; } } if (flag == 0) { Pop(s); } } printf(" }\n"); } } Node Popl(qLine s) { Node n; s->top++; n = s->a[s->top]; return n; } void Pushl(qLine s, Node n) { s->end++; s->a[s->end] = n; } //遍历 void LookAlL (int a[][10], qLine s, int *b, int numbers) { int count = 0, m = 0; while (count != numbers) { for (int k = 0; k < numbers; k++) { if (b[k] == 0) { m = k; break; } } Node N; N.y = m; printf("{"); Pushl(s, N); b[N.y] = 1; while (s->top != s->end) { Node x = Popl(s); printf(" %d", x.y); count++; b[x.y] = 1; for (int i = 0; i <numbers; i++) { if (a[x.y][i] == 1 && b[i] != 1) { Node n; n.y = i; Pushl(s, n); b[n.y] = 1; } } } printf(" }\n"); } } int main() { int a[10][10] = { 0 }; int n, L; scanf("%d %d", &n, &L); int b[10] = { 0 }; int c[10] = { 0 }; int x, y; for (int i = 0; i < L; i++) { scanf("%d %d", &x, &y); a[x][y] = 1; a[y][x] = 1; } a; qLine q = (Line *)malloc(sizeof(Line)); q->end = 0; q->top = 0; qStack p = (Stack *)malloc(sizeof(Stack)); p->top = -1; LookAll(a, p, b, n); LookAlL(a, q, c, n); system("pause"); return 0; }