1. 程式人生 > >演算法之路(三)——BFS

演算法之路(三)——BFS

最近由於要忙論文開題的事,還有實習工作也比較忙,所以這個系列的部落格好久沒有更新了。

BFS是一種基於“佇列”這種資料結構的搜尋方式,特點是由一個狀態拓展出很多狀態,然後再由此擴充套件,直到找到目標狀態或者佇列中頭尾指標相遇,即佇列中所有狀態都處理完畢。

BFS對於解決最短或最少問題特別有效,而且尋找深度小,但缺點也很明顯,記憶體消耗巨大(因為它需要大量的陣列單元用來儲存狀態)。

下面是實現BFS的C++程式碼:

 1 #include <iostream>
 2 #include <queue>
 3 using namespace std;
 4 
 5 #define
MAX 20 6 #define START 1 7 8 int visited[MAX]; 9 int map[MAX][MAX]; 10 11 void bfs(int start, int n){ 12 queue<int> q; 13 int q_top; 14 cout<<start<<" "; 15 visited[start] = 1; 16 for (int i = 1; i <= n ;i++ ) { 17 if(map[start][i] == 1 && visited[i] == 0
){ 18 q.push(i); 19 visited[i] = 1; 20 } 21 } 22 while(!q.empty()){ 23 q_top = q.front(); 24 q.pop(); 25 cout<<q_top<<" "; 26 for(int i = 1; i <= n; i++ ){ 27 if(map[q_top][i] == 1 && visited[i] == 0
){ 28 q.push(i); 29 visited[i] = 1; 30 } 31 } 32 } 33 34 } 35 36 int main(int argc, const char * argv[]) { 37 int num_vex,num_edge,x,y; 38 cout<<"Input number of nodes and edges >> "; 39 cin>>num_vex>>num_edge; 40 for(int i=0;i<MAX;i++){ 41 for(int j = 0;j < MAX;j++){ 42 map[i][j] = 0; 43 } 44 } 45 for(int i = 1;i <= num_vex;i++){ 46 visited[i] = 0; 47 } 48 cout<<"Input edges, "<<num_edge<<" left >> "; 49 for(int i = 1;i <= num_edge;i++){ 50 cin>>x>>y; 51 map[x][y] = map[y][x] = 1; 52 cout<<"Input edges, "<<(num_edge-i)<<" left >> "; 53 } 54 bfs(START, num_vex); 55 return 0; 56 }

執行結果為:

[email protected]:~/Linux_pro/code_resource/algorithm/BFS$ g++ -o main.cpp
g++: fatal error: no input files
compilation terminated.
[email protected]:~/Linux_pro/code_resource/algorithm/BFS$ g++ -o out main.cpp
[email protected]-OptiPlex-9020:~/Linux_pro/code_resource/algorithm/BFS$
[email protected]:~/Linux_pro/code_resource/algorithm/BFS$
[email protected]:~/Linux_pro/code_resource/algorithm/BFS$ ll
total 112
drwxrwxr-x 2 lpq lpq   4096  3月 26 01:02 ./
drwxrwxr-x 4 lpq lpq   4096  3月 26 00:13 ../
-rw-rw-r-- 1 lpq lpq   2825  3月 26 00:46 main.cpp
-rwxrwxr-x 1 lpq lpq 101104  3月 26 01:02 out*
[email protected]:~/Linux_pro/code_resource/algorithm/BFS$ ./out
6
0 1
0 2
0 3
1 4
1 5
2 6
top:
0
距離top最遠的節點的條數: 2

order:
0 1 2 3 4 5 6

小結:

BFS的思想:


(1)頂點v入佇列。
(2)當佇列非空時則繼續執行,否則演算法結束。
(3)出佇列取得隊頭頂點v;訪問頂點v並標記頂點v已被訪問。
(4)查詢頂點v的第一個鄰接頂點col。
(5)若v的鄰接頂點col未被訪問過的,則col入佇列。
(6)繼續查詢頂點v的另一個新的鄰接頂點col,轉到步驟(5)。直到頂點v的所有未被訪問過的鄰接點處理完。轉到步驟(2)。