算法之路(三)——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 }

运行结果为:

lpq@lpq-OptiPlex-9020:~/Linux_pro/code_resource/algorithm/BFS$ g++ -o main.cpp
g++: fatal error: no input files
compilation terminated.
lpq@lpq-OptiPlex-9020:~/Linux_pro/code_resource/algorithm/BFS$ g++ -o out main.cpp
lpq@lpq-OptiPlex-9020:~/Linux_pro/code_resource/algorithm/BFS$
lpq@lpq-OptiPlex-9020:~/Linux_pro/code_resource/algorithm/BFS$
lpq@lpq-OptiPlex-9020:~/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*
lpq@lpq-OptiPlex-9020:~/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)。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值