BFS and queues

  Depth-first search (DFS) and breadth-first search (BFS) is the basic technology of violence, often used to solve the diagram, the tree traversal issue.

  Consider first algorithm ideas. Mouse Maze at an example:

  (1): a rat maze. It chose to go at each intersection to the right, until hitting the wall can not move forward, then a step back, and this time take the left, then continue to go down. In this way can be traveled all the way, and will not be repeated . The idea is to DFS.

  (2): a group of mice maze. Mice are an infinite number of assumptions, these mice went in, sending part of the mice to explore the road not traveled at each intersection. Mice go a certain route, and can not move forward if run into a wall, and stopped; If you reach the intersection already has explored other mice, and also to stop. It is clear that all roads will come, and will not be repeated . The idea is to BFS.

  

  A - Red and Black 

 

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 Input

6 9
....#.
.....#
......
......
......
......
......
#@...#
.#..#.
11 9
.#.........
.#.#######.
.#.#.....#.
.#.#.###.#.
.#.#..@#.#.
.#.#####.#.
.#.......#.
.#########.
...........
11 6
..#..#..#..
..#..#..#..
..#..#..###
..#..#..#@.
..#..#..#..
..#..#..#..
7 7
..#.#..
..#.#..
###.###
...@...
###.###
..#.#..
..#.#..
0 0

Sample Output

45
59
6
13
  Subject to the effect: "#" is equivalent to not go traps or walls, is the way to go. "." From @ point, the total number of locations can reach statistical 

 code for a: This is used to bite the bullet and check algorithm sets Beginners disjoint-set to solve the problem of 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 }
View Code
 

  Code II: It's also hard to tell when the DFS algorithm written DFS and BFS (much simpler than the back of the BFS, BFS do not know why as examples on here)

 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 ++) { // four forward direction 
12 is          int TX MOV = X + [I] [ 0 ];
 13 is          int TY = Y + MOV [I] [ . 1 ];
 14  
15          IF (S [TX] [TY] == ' . ' && TX> = 0 && TX <&& TY H> = 0 && TY < W)
 16              DFS (TX, TY); // after determining the possible points to enter the DFS 
. 17      }
 18 is  }
 . 19  
20 is 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 }
View Code

 

  Code Three: Quoted from solving the code BFS algorithm "algorithm contest entry to advanced" in the

. 1 #include <bits / STDC ++ H.>
 2  the using  namespace STD;
 . 3  
. 4  char Room [ 23 is ] [ 23 is ];
 . 5  int the dir [ . 4 ] [ 2 ] = { // upper left corner coordinates are (0,0) 
6      {- 1 , 0 },      // left 
7      { 0 , - 1 },      // upwardly 
8      { 1 , 0 },      // rightward 
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); // inserted into the queue 
23 is      
24      the while (! q.empty ()) { // until the queue is empty 
25          Start q.front = (); // take the head of the queue elements, i.e., circulating round starting point 
26 is          q.pop (); // delete the head of the queue elements (take out) 
27          
28          for ( int I = 0 ; I < . 4 ; I ++) { // left lower right four directions individually search 
29              next.x = the dir + start.x [I] [ 0 ];
 30              next.y + = start.y the dir [I] [ . 1 ];
 31 is              IF (Check (next.x, next.y) && Room [next.x] [ next.y] == '. ' ) { 
 32                  Room [next.x] [next.y] = ' # ' ; // tag has gone through 
33 is                  NUM ++; // count 
34 is                  ; q.push (Next) // After this determination of the feasible , enqueue, to be recycled is determined 
35              }
 36          }
 37 [      }
 38 is  } 
 39  
40  int main () {
 41 is      int X, Y, DX, Dy;
 42 is      the while (~ Scanf ( " % D% D " , & of Wx, & Hy) ) {
 43 is          IF (== of Wx0 && 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 is          NUM = 0 ; // initialize 
55          the BFS (DX, Dy);
 56 is          the printf ( " % D \ n- " , NUM);
 57 is      }
 58      return  0 ;
 59 }
View Code

   Here temporarily sorted out the code for this question about DFS and BFS algorithm, DFS is relatively easy to understand, recursive thinking has long been in contact, relatively easy to use; BFS also involves knowledge queue queue, understand the difficulties beginners, even here finishing out, there is no guarantee can write out the next time you encounter.

  With a code that is thought disjoint-set, because for the first time to do this when the subject just learning disjoint-set, took out with a fresh, really worn scalp, especially when you see the code after the DFS, I now a chance to not believe this is my time to write code? Disjoint-set of thinking need to know, but the thing is to determine clear case of questions type, choose a relatively simple and convenient, as well as their grasp of skilled algorithm.

  Second, the code is written in a vaguely listening to the DFS and BFS after the code, which I now most acceptable recommended code, the use of recursion key is to find exactly the contact before and after, recursive code looks simple, but it really hit new title, may have the toss. Regardless of DFS or BFS check some of these have similar size, that before taking the next steps to determine the point to go, whether within a given range (may also be cross-border in their own array), and relevant symbol indicates had here to avoid double counting, or prevent the recursive loop does not end.

  Third, the BFS algorithm on the code book should be standard "template" and now on vector, queue, STL sequence container map such understanding is not deep, control failure, the use of good, even if the copy the template, but also to practice Related topics familiar techniques such rules kinds of questions. queue of .front () .pop () using BFS .push () addressing topics important operations, queue is a tool to solve the shortest path here reflect much.

(Diligently practiced, ground write blog) 2020/1/18/21/28

Guess you like

Origin www.cnblogs.com/0424lrn/p/12210298.html