1. 程式人生 > >廣度優先搜尋(鄰接表)

廣度優先搜尋(鄰接表)

#include <iostream>
#include <cstdio>
#include <vector>
#include <queue>

using namespace std;

struct Node{
    //to 代表每個節點
    //next 代表下一個元素的編號
    int to,next;
}e[100];

int head[100] = {0};
int cnt = 0;

//暫時儲存待遍歷點
queue<int> q;
//做標誌
bool vis[100] = {false};

//建立鄰接表
void add(int a,int b){
    //cnt 用於記錄每個點的編號
    cnt++;

    //a 的鄰接表頭插入 b
    e[cnt].next = head[a];
    e[cnt].to = b;

    //頭插入後 將a鄰接表的頭的編號修改
    head[a] = cnt;
}

//廣度優先搜尋
void BFS(int n){

    vis[n] = true;//主要針對第一個元素

    //遍歷 n 列表對應的鄰接表
    for(int i = head[n];i != 0;i = e[i].next){

        if(vis[e[i].to] == false){
            q.push(e[i].to);//當這個節點沒有被訪問過 則 入隊
            vis[e[i].to] = true;//標誌節點被訪問了
        }
    }

}
void BFSTraver(int ft){
    //搜尋開始的節點ft
    q.push(ft);

    while (!q.empty()) {

            cout << q.front() << " ";

            BFS(q.front());
            //遍歷q.front()所對應的鄰接表後 就刪除
            q.pop();
    }
}
int main(int argc, char const *argv[]) {
    //N->幾條路徑
    int N;

    printf("please input the number of rode:");
    scanf("%d",&N);

    printf("please input every rode:\n");
    for(int i = 0;i < N;i++){
        int a,b;
        scanf("%d%d",&a,&b);

        //建立鄰接表
        add(a,b);
        add(b,a);
    }
    // for(int i = 1;i <= N;i++){
    //     for(int j = head[i];j != 0;j = e[j].next){
    //         printf("%d ",e[j].to);
    //     }
    //     printf("\n");
    // }

    printf("please input the first point:");
    //遍歷的第一個節點
    int ft;

    scanf("%d",&ft);

    printf("BFS:\n");
    BFSTraver(ft);

    printf("\n");
    return 0;
}