日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

二十三、图的广度优先遍历

發布時間:2025/3/21 编程问答 21 豆豆
生活随笔 收集整理的這篇文章主要介紹了 二十三、图的广度优先遍历 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

二十三、圖的廣度優先遍歷

文章目錄

  • 二十三、圖的廣度優先遍歷
    • 題目描述
    • 解題思路
    • 上機代碼

題目描述

程序的輸入是無向圖的頂點序列和邊序列(頂點序列以*為結束標志,邊序列以-1,-1為結束標志)。程序的輸出為圖的鄰接表和廣度優先遍歷序列。例如:

程序輸入為:
a
b
c
d
e
f
*
0,1
0,4
1,4
1,5
2,3
2,5
3,5
-1,-1

程序的輸出為:
the ALGraph is
a 4 1
b 5 4 0
c 5 3
d 5 2
e 1 0
f 3 2 1
the Breadth-First-Seacrh list:aebfdc

測試輸入期待的輸出時間限制內存限制額外進程
測試用例 1a
b
c
d
e
f
*
0,1
0,4
1,4
1,5
2,3
2,5
3,5
-1,-1
the ALGraph is
a 4 1
b 5 4 0
c 5 3
d 5 2
e 1 0
f 3 2 1
the Breadth-First-Seacrh list:aebfdc
1秒64M0

解題思路

用一個 node 結構來模擬鄰接表,data表示邊表的頭結點(頭結點可能不止一個字符,最好用字符數組),num表示該邊表中依附了幾個結點,list[] 數組存儲依附的結點編號,map[] 數組模擬頂點表,這樣一個鄰接表就模擬出來了。

同時,因為我們在之后還要進行廣度優先遍歷,所以還需要添加一個標記位 vis,來檢測當前結點是否被標記過。

struct node {char data[10]; //邊表頭結點int list[100]; //邊表中各個結點編號int num; //邊表中連接的結點數int vis; //標記位 }map[100]; //頂點表

一點值得注意的是,本題輸入的是無向圖,所以對于一條輸入的邊序列(x,y),我們需要建立兩條邊。

map[x].list[map[x].num] = y; map[x].num++; map[y].list[map[y].num] = x; map[y].num++;

當我們用 bfs 遍歷求解時,為了避免多次重復遍歷,用一個 for 循環,判斷結點的 vis 不為 0,則跳過該結點的遍歷。

上機代碼

#include<cstdio> #include<cstring> #include<cstdlib> #include<queue> #include<algorithm> using namespace std; struct node {char data[10];//邊表頭結點int list[100];//邊表中各個結點編號int num; //邊表中連接的結點數int vis; //標記位 }map[100]; //頂點表 int counts = 0, x, y;void bfs(int n) {queue<int>q;int ans = n;int tmp;map[ans].vis = 1;q.push(ans);while (!q.empty()){ans = q.front();q.pop();printf("%c", map[ans].data[0]);if (map[ans].num == 0)continue;for (int k = map[ans].num - 1; k >= 0; k--){tmp = map[ans].list[k];if (map[tmp].vis == 1)continue;q.push(tmp);map[tmp].vis = 1;}} } int main() {while (~scanf("%s",&map[counts].data))//輸入節點{if (map[counts].data[0] == '*')break;counts++;}while (~scanf("%d,%d", &x, &y))//輸入鄰接表{if (x == -1 && y == -1)//結束標志break;//無向圖需要建立兩條邊map[x].list[map[x].num] = y;map[x].num++;map[y].list[map[y].num] = x;map[y].num++;}printf("the ALGraph is\n");for (int i = 0; i < counts; i++)//打印鄰接表{printf("%c", map[i].data[0]);for (int j = map[i].num - 1; j >= 0; j--){printf(" %d", map[i].list[j]);}printf("\n");}printf("the Breadth-First-Seacrh list:");for (int i = 0; i < counts; i++)//bfs序列{if (map[i].vis == 0)bfs(i);}printf("\n");//system("pause");return 0; }

總結

以上是生活随笔為你收集整理的二十三、图的广度优先遍历的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。