深度优先搜索(DFS)和广度优先搜索(BFS)是基本的暴力技术,常用于解决图、树的遍历问题。
首先考虑算法思路。以老鼠走迷宫为例:
(1):一只老鼠走迷宫。它在每个路口都选择先走右边,直到碰壁无法继续前进,然后回退一步,这一次走左边,接着继续往下走。用这个办法能走遍所有的路,而且不会重复。这个思路就是DFS。
(2):一群老鼠走迷宫。假设老鼠是无限多的,这群老鼠进去后,在每个路口派出部分老鼠探索没有走过的路。走某条路的老鼠,如果碰壁无法前进,就停下;如果到达的路口已经有其他的老鼠探索过了,也停下。很显然,所有的道路都会走到,而且不会重复。这个思路就是BFS。
There is a rectangular room, covered with square tiles. Each tile is colored either red or black. A man is standing on a black tile. From a tile, he can move to one of four adjacent tiles. But he can't move on red tiles, he can move only on black tiles.
Write a program to count the number of black tiles which he can reach by repeating the moves described above.InputThe input consists of multiple data sets. A data set starts with a line containing two positive integers W and H; W and H are the numbers of tiles in the x- and y- directions, respectively. W and H are not more than 20.
There are H more lines in the data set, each of which includes W characters. Each character represents the color of a tile as follows.
'.' - a black tile
'#' - a red tile
'@' - a man on a black tile(appears exactly once in a data set)
OutputFor each data set, your program should output a line which contains the number of tiles he can reach from the initial tile (including itself).
Sample Input6 9 ....#. .....# ...... ...... ...... ...... ...... #@...# .#..#. 11 9 .#......... .#.#######. .#.#.....#. .#.#.###.#. .#.#..@#.#. .#.#####.#. .#.......#. .#########. ........... 11 6 ..#..#..#.. ..#..#..#.. ..#..#..### ..#..#..#@. ..#..#..#.. ..#..#..#.. 7 7 ..#.#.. ..#.#.. ###.### ...@... ###.### ..#.#.. ..#.#.. 0 0Sample Output
45 59 6 13
题目大意:“#”相当于不能走的陷阱或墙壁,“.”是可以走的路。从@点出发,统计所能到达的地点总数 代码一:这是初学并查集时硬着头皮用并查集的算法解决了BFS的问题

1 #include<iostream>
2 using namespace std;
3
4 const int h = 22;
5 char map[h][h];
6 int key[h*h];
7 int rrank[h*h];
8 int n,m,dx,dy;
9
10 int find(int a){
11 return a==key[a]? a : key[a]=find(key[a]);
12 }
13
14 void key_union(int a,int c){
15 int fa = find(a);
16 int fc = find(c);
17 if(rrank[fa]>rrank[fc])
18 key[fc] = fa;
19 else{
20 key[fa] = fc;
21 if(rrank[fa]==rrank[fc])
22 rrank[fc]++;
23 }
24 }
25
26 int num(int a){
27 int k = find(a);
28 int ans = 0;
29 for(int i=1;i<=m;i++)
30 for(int j=1;j<=n;j++)
31 if(find(i*n+j)==k)
32 ans++;
33
34 return ans;
35 }
36
37 int main()
38 {
39 while(scanf("%d %d",&n,&m)!=EOF){
40 if(n==0&&m==0) break;
41 for(int i=1;i<=m;i++){
42 cin.get();
43 for(int j=1;j<=n;j++){
44 scanf("%c",&map[i][j]);
45 if(map[i][j]!='#') key[i*n+j] = i*n+j;
46 else key[i*n+j] = 0;
47 if(map[i][j]=='@'){//找到@的坐标
48 dx = i;
49 dy = j;
50 map[i][j] = '.';
51 }
52 }
53 }
54
55 for(int i=1;i<m;i++){
56 for(int j=1;j<n;j++){
57 if(key[i*n+j]){
58 if(key[i*n+j+1])
59 key_union(i*n+j,i*n+j+1);
60 if(key[i*n+n+j])
61 key_union(i*n+n+j,i*n+j);
62 }
63 }
64 if(key[i*n+n])
65 if(key[i*n+2*n])
66 key_union(i*n+2*n,i*n+n);
67 }
68 for(int i=1;i<n;i++)
69 if(key[m*n+i])
70 if(key[m*n+i+1])
71 key_union(m*n+i,m*n+i+1);
72
73 int ans = num(dx*n+dy);
74 printf("%d\n",ans);
75 }
76 }
代码二:这是还分不清DFS和BFS时写的DFS算法(比后面的BFS要简洁很多,不知道为什么作为BFS的例题放在这里)

1 #include<iostream>
2 using namespace std;
3
4 int mov[4][2] = {-1,0,1,0,0,-1,0,1};
5 int sum,w,h;
6 char s[21][21];
7
8 void dfs(int x,int y){
9 sum++;//计数
10 s[x][y] = '#';
11 for(int i=0;i<4;++i){//四个方向前进
12 int tx = x+mov[i][0];
13 int ty = y+mov[i][1];
14
15 if(s[tx][ty]=='.' && tx>=0 && tx<h && ty>=0 && ty<w)
16 dfs(tx,ty);//判断该点可行后进入dfs
17 }
18 }
19
20 int main()
21 {
22 int x,y;
23 while(scanf("%d %d",&w,&h)!=EOF){
24 if(w==0&&h==0) break;
25 for(int i=0;i<h;i++){
26 cin.get();
27 for(int j=0;j<w;j++){
28 scanf("%c",&s[i][j]);
29 if(s[i][j]=='@'){//起点
30 x = i;
31 y = j;
32 }
33 }
34 }
35 sum = 0;
36 dfs(x,y);
37 printf("%d\n",sum);
38 }
39 return 0;
40 }
代码三:引自《算法竞赛入门到进阶》中的解题代码 BFS算法

1 #include<bits/stdc++.h>
2 using namespace std;
3
4 char room[23][23];
5 int dir[4][2] = { //左上角的坐标是(0,0)
6 {-1, 0}, //向左
7 {0, -1}, //向上
8 {1, 0}, //向右
9 {0, -1} //向下
10 };
11
12 int Wx, Hy, num;
13 #define check(x, y)(x<Wx && x>=0 && y>=0 && y<Hy) //是否在room中
14 struct node{int x, y};
15
16 void BFS(int dx, int dy){
17 num = 1;
18 queue<node> q;
19 node start, next;
20 start.x = dx;
21 start.y = dy;
22 q.push(start);//插入队列
23
24 while(!q.empty()){//直到队列为空
25 start = q.front();//取队首元素,即此轮循环的出发点
26 q.pop();//删除队首元素(以取出)
27
28 for(int i=0; i<4; i++){//往左上右下四个方向逐一搜索
29 next.x = start.x + dir[i][0];
30 next.y = start.y + dir[i][1];
31 if(check(next.x, next.y) && room[next.x][next.y]=='.'){
32 room[next.x][next.y] = '#';//标记已经走过
33 num ++;//计数
34 q.push(next);//判断此点可行之后,插入队列,待循环判断
35 }
36 }
37 }
38 }
39
40 int main(){
41 int x, y, dx, dy;
42 while(~scanf("%d %d",&Wx, &Hy)){
43 if(Wx==0 && Hy==0)
44 break;
45 for(y=0; y<Hy; y++){
46 for(x=0; x<Wx; x++){
47 scanf("%d",&room[x][y]);
48 if(room[x][y] == '@'){//找到起点坐标
49 dx = x;
50 dy = y;
51 }
52 }
53 }
54 num = 0;//初始化
55 BFS(dx, dy);
56 printf("%d\n",num);
57 }
58 return 0;
59 }
这里暂时整理出了此题的关于DFS和BFS算法的代码,DFS相对好理解,递归的思想早有接触,相对易用;BFS还涉及到queue队列的知识,初学时理解困难,即使此处整理出,也不能保证下次遇到时还能写的出来。
代码一用的是并查集的思想,因为第一次做这个题目的时候刚学并查集,新鲜就拿出来用了,确实是磨破了头皮,尤其当看到DFS的代码以后,我现在再拿出来都不敢相信这是我当时写的代码?并查集的思想需要掌握,但是遇题还是要先判断清楚类型,选择相对简易方便、以及自己掌握熟练的算法。
代码二是在模糊地听完了DFS和BFS以后写出来的代码,也是我现在最能接受的简易代码,递归的运用关键在于准确找到前后的联系,递归的代码看上去简单,但是真的遇到新题,可就有的折腾了。这类题型中不管DFS还是BFS都有相似的check部分,即在走出下一步之前,要判断将要走的点,是否在给定范围之内(也有可能在自己的数组中越界),并有相关标记,表示此处来过,避免重复计数,防止递归或循环没有尽头。
代码三是书上的BFS算法,应该是标准的“模板了”,现在关于vector、queue、map之类的STL序列容器理解不深,掌握不全,运用不好,就算抄模板,也要多练习相关题目,熟悉此类题型的技巧规则。queue的.front() .pop() .push()时运用BFS解决题目的重要操作,queue是解决最短路径的利器,此处体现不多。
(勤加练习,勤写博客)2020/1/18/21:28
来源:https://www.cnblogs.com/0424lrn/p/12210298.html
