解题代码
#include<stdio.h>
#define MAXN 1000
#define MAXM (33*MAXN)
typedef enum { false, true } bool;
int A[MAXN+1][MAXN+1], B[MAXN+1], Q[MAXN+1];
int N, front = -1, rear = -1;
void Clear(void);
int BFS(int V);
int Dequeue(void);
void Enqueue(int V);
bool IsEmpty(void);
int main()
{
int M, i, x, y, counter, flag = 1;
scanf("%d %d", &N, &M);
for (i = 0; i < M; i++) {
scanf("%d %d", &x, &y);
A[x][y] = 1;
}
for (i = 1; i <= N; i++) {
counter = BFS(i);
if (flag) flag = 0;
else printf("\n");
printf("%d: %.2lf%%", i, (double)counter / N * 100);
Clear();
}
return 0;
}
void Clear(void) {
for (int i = 1; i <= N; i++) {
B[i] = 0;
Q[i] = 0;
front = rear = -1;
}
}
int BFS(int V) {
int counter = 1, level = 0, last = V, tail;
B[V] = 1;
Enqueue(V);
while (!IsEmpty()) {
V = Dequeue();
for (int i = 1; i <= N; i++) {
if (!B[i] && (A[i][V] || A[V][i])) {
B[i] = 1;
counter++;
Enqueue(i);
tail = i;
}
}
if (V == last) {
level++;
last = tail;
}
if (level == 6) break;
}
return counter;
}
int Dequeue(void) {
return Q[++front];
}
void Enqueue(int V) {
Q[++rear] = V;
}
bool IsEmpty(void) {
if (front == rear) return true;
else return false;
}
测试结果
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/e99f360d18a8740543c735d2bab5be93.png)
问题整理
1.这种题一定不要忘记Clear。