zoukankan      html  css  js  c++  java
  • network of emergency contacts---BFS

    本题目的主要难点在如何寻找最后一层的数,利用book标记数组可以很好的解决问题。book=0的时候说明没被连接过,若要连接时,将book等于上一层book+1.

    需要注意的是,对于图的问题建立邻接矩阵是非常省时间的方法。类似这个道题,我没有用邻接矩阵,因此每次都要进入150的for循环。但是如果用矩阵,最多则是每次100的循环。这样对于n*n*n.....来说则会剩下很多时间。

    #include<stdio.h>
    #include<stdlib.h>
    typedef struct{
        int a[300];
        int rear;
        int head;
    }queue;
    queue q;
    int A[150],B[150];
    int book[300];
    int test(int data[300],int startNum);
    void build(int data[300]){
        for(int i=0;i<300;i++)
            data[i]=rand()%100+1;
    }
    void main(){
        //freopen("intput.txt","r",stdin);
        int data[300];
        for(int l=0;l<10;l++){
            build(data);
            printf("%d
    ",test(data,data[0]));
        }
    }
    int test(int data[300],int startNum){
        for(int i=0;i<300;i++)
            book[i]=0;
        for(int i=0,j=0;i<299;j++){          //将数据分为两个数组中A表示边的出发点,B表示边的终点
            A[j]=data[i];
            B[j]=data[i+1];
            i=i+2;
        }
        q.rear=0;
        q.head=0;
        q.a[q.rear++]=startNum;
        book[startNum]=1;
        while(q.head<q.rear){
            int temp=q.a[q.head++];
            for(int i=0;i<150;i++){
                if(A[i]==temp&&book[B[i]]==0){
                    q.a[q.rear++]=B[i];
                    book[B[i]]=book[A[i]]+1;     //标记层数
                }
            }
        }
        int c=0;
        int max=0;
        for(int i=0;i<=299;i++){            //寻找最大层数
            if(c<book[i]){
                c=book[i];
            }
        }
        for(int i=299;i>=0;i--){            //寻找最大层数总最大值
            if(book[i]==c){
                max=i;
                break;
            }
        }
        return max;
    }
  • 相关阅读:
    Laravel 初始化
    ant design pro 左上角 logo 修改
    请求到服务端后是怎么处理的
    Websocket 知识点
    王道数据结构 (7) KMP 算法
    王道数据结构 (6) 简单的模式匹配算法
    王道数据结构 (4) 单链表 删除节点
    王道数据结构 (3) 单链表 插入节点
    王道数据结构 (2) 单链表 尾插法
    王道数据结构 (1) 单链表 头插法
  • 原文地址:https://www.cnblogs.com/lvcoding/p/6600355.html
Copyright © 2011-2022 走看看