图的广度优先遍历-06-图3 六度空间

  • 题目
    06-图3 六度空间 (30分)
  • 分析
    本题需要输出距离不超过6的结点数占结点总数的百分比,首先肯定想到要用广度优先遍历(BFS),而且只需要遍历6层以内的结点。可以用一个变量level来记录层数,一旦达到6层便停止遍历,计算输出。
  • 我的代码
#include<iostream>
#include<queue>
using namespace std;

int const MAXN = 10001;
int person[MAXN];
int N,M;

bool visited[MAXN];
queue<int> Q;

typedef struct NODE* ptrNode;
struct NODE{
    int data;
    struct NODE* link;
};

ptrNode heads[MAXN];

void insertXY(int x, int y)
{
    ptrNode t1,t2;
    t1 = (ptrNode)malloc(sizeof(struct NODE));
    t1->data = y;
    t1->link = heads[x]->link;
    heads[x]->link = t1;

    t2 = (ptrNode)malloc(sizeof(struct NODE));
    t2->data = x;
    t2->link = heads[y]->link;
    heads[y]->link = t2;
}

int BFS(int x)
{
    int count = 1, level = 0, last = x, tail;
    int i;
    //初始化工作 
    while(!Q.empty()) Q.pop();
    for(i=1;i<=N; i++){
        visited[i] = false;
    }
    //开始搜索计数 
    visited[x] = true;
    Q.push(x);
    while(!Q.empty()){
        int v = Q.front();
        Q.pop();

        ptrNode tmp = heads[v]->link;
        while(tmp != NULL){
            if(!visited[tmp->data]){
                visited[tmp->data] = true;
                Q.push(tmp->data);
                count++;
                tail = tmp->data;
            }
            tmp = tmp->link;
        }

        if(v == last){
            level++;
            last = tail;
        }
        if(level == 6)  break;  
    }

    return count;
} 

int main()
{
    #ifndef ONLINE_JUDGE
    freopen("666.txt","r",stdin);
    #endif

    int i,x,y;
    scanf("%d%d",&N, &M);

    for(i=1; i<=N; i++){
        heads[i] = (ptrNode)malloc(sizeof(struct NODE));
        heads[i]->data = i;
        heads[i]->link = NULL;
    }

    for(i=1; i<=M; i++){
        scanf("%d%d",&x,&y);
        insertXY(x,y);
    }

    for(i=1; i<=N; i++){
        int ans = BFS(i);
        printf("%d: %.2f%%\n", i, (float)ans*100/N);
    }
    return 0;
} 
    原文作者:数据结构之图
    原文地址: https://blog.csdn.net/bobo1356/article/details/72676788
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞