二十三、图的广度优先遍历
生活随笔
收集整理的這篇文章主要介紹了
二十三、图的广度优先遍历
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
二十三、圖的廣度優先遍歷
文章目錄
- 二十三、圖的廣度優先遍歷
- 題目描述
- 解題思路
- 上機代碼
題目描述
程序的輸入是無向圖的頂點序列和邊序列(頂點序列以*為結束標志,邊序列以-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
| 測試用例 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 | 1秒 | 64M | 0 |
解題思路
用一個 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; }總結
以上是生活随笔為你收集整理的二十三、图的广度优先遍历的全部內容,希望文章能夠幫你解決所遇到的問題。