network of emergency contacts---BFS

來源:互聯網
上載者:User

標籤:UI   表示   問題   lib   bfs   printf   如何   鄰接矩陣   logs   

本題目的主要痛點在如何尋找最後一層的數,利用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\n",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;}

 

network of emergency contacts---BFS

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.