今天做到了dfs的训练,感觉和bfs有相似之处,接下来用一道题来总结一下方法,可类比bfs。
上题:
Description
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.
Write a program to count the number of black tiles which he can reach by repeating the moves described above.
Input
The 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)
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)
Output
For 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
#include<stdio.h> #include<string.h> char point[25][25]; bool flag[25][25]; //flag对应着我们需要研究的点point,用来标记是否曾经到过 int dx[4]={1,-1,0,0}; int dy[4]={0,0,-1,1}; int count; void dfs(int x0,int y0,int r,int c) { for(int i=0;i<4;i++) //for循环用来探索所有邻接点 { int tempx=x0+dx[i],tempy=y0+dy[i]; if(tempx<c&&tempx>=0&&tempy<r&&tempy>=0&&flag[tempy][tempx]==false&&point[tempy][tempx]=='.') { count++; flag[tempy][tempx]=true; //满足条件且未标记的标记上 dfs(tempx,tempy,r,c); //通过递归来实现顺藤摸瓜的效果 } } return ; } void make_set() { for(int i=0;i<25;i++) for(int j=0;j<25;j++) flag[i][j]=false; return ; } int main() { int c,r,x0,y0; while(1) { count=1; scanf("%d%d",&c,&r); getchar(); if(c==0&&r==0) break; for(int i=0;i<r;i++) { for(int j=0;j<c;j++) { point[i][j]=getchar(); if(point[i][j]=='@') { x0=j; y0=i; } } getchar(); } make_set(); dfs(x0,y0,r,c); printf("%d\n",count); } return 0; }
与bfs的区别:bfs是通过队列来进行逐层探索,而dfs则是沿着一个路径探索下去一直到底,到底后再返回沿其他路径探索,就和顺藤摸瓜差不多,大体上两者达到的效果基本一致(特殊情况效果有区别),两者均有缺点,bfs在编写代码时较麻烦,用到队列,一般要使用结构体,而dfs则是由于其使用递归调用,大数据易超时。
==================================================================================================================================
赶紧跑回来加一句:最短路径用bfs!!