forked from Yuri0314/PTA-mooc
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path06-图1 列出连通集.c
133 lines (117 loc) · 2.38 KB
/
06-图1 列出连通集.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
#include <stdio.h>
#include <stdlib.h>
#define MAXN 10
int graph[MAXN][MAXN] = {0};
int visitedDFS[MAXN] = {0};
int visitedBFS[MAXN] = {0};
/* 队列定义开始 */
#define MaxSize 11
#define ERROR -1
typedef int Position;
struct QNode {
int *Data; /* 存储元素的数组 */
Position Front, Rear; /* 队列的头、尾指针 */
};
typedef struct QNode *Queue;
Queue CreateQueue()
{
Queue Q = (Queue)malloc(sizeof(struct QNode));
Q->Data = (int *)malloc(MaxSize * sizeof(int));
Q->Front = Q->Rear = 0;
return Q;
}
void DestoryQueue( Queue Q )
{
if (Q->Data) free(Q->Data);
free(Q);
}
int IsFull( Queue Q )
{
return ((Q->Rear+1)%MaxSize == Q->Front);
}
void Enqueue( Queue Q, int X )
{
if ( IsFull(Q) ) return;
else {
Q->Rear = (Q->Rear+1)%MaxSize;
Q->Data[Q->Rear] = X;
}
}
int IsEmpty( Queue Q )
{
return (Q->Front == Q->Rear);
}
int Dequeue( Queue Q )
{
if ( IsEmpty(Q) ) return ERROR;
else {
Q->Front =(Q->Front+1)%MaxSize;
return Q->Data[Q->Front];
}
}
/* 队列定义结束 */
void createGraph(int edges)
{
int i, j, k;
for (k = 0; k < edges; ++k) {
scanf("%d %d", &i, &j);
graph[i][j] = 1;
graph[j][i] = 1;
}
}
void DFS(int vertex, int nodes)
{
int i, j;
visitedDFS[vertex] = 1;
printf("%d ", vertex);
for (i = vertex, j = 0; j < nodes; ++j) {
if (graph[i][j] == 1 && !visitedDFS[j])
DFS(j, nodes);
}
}
void BFS(int vertex, int nodes)
{
int tmp, i, j;
Queue Q;
Q = CreateQueue();
visitedBFS[vertex] = 1;
printf("%d ", vertex);
Enqueue(Q, vertex);
while(!IsEmpty(Q)) {
tmp = Dequeue(Q);
for (i = tmp, j = 0; j < nodes; ++j) {
if (graph[i][j] == 1 && !visitedBFS[j]) {
visitedBFS[j] = 1;
printf("%d ", j);
Enqueue(Q, j);
}
}
}
DestoryQueue(Q);
}
void ListComponents (int nodes)
{
int i;
for (i = 0; i < nodes; ++i) {
if (!visitedDFS[i]) {
printf("{ ");
DFS(i, nodes);
printf("}\n");
}
}
for (i = 0; i < nodes; ++i) {
if (!visitedBFS[i]) {
printf("{ ");
BFS(i, nodes);
printf("}\n");
}
}
}
int main()
{
int N, E;
scanf("%d %d", &N, &E);
createGraph(E);
ListComponents(N);
return 0;
}