其实吧!DFS我早都学过了,但是一直都不敢写这一篇博客,因为啥?因为感觉自己学艺不精啊,BFS和DFS都是一种搜索算法,我感觉BFS没有那么难,因为他比较好理解,但是DFS因为牵扯到递归和回溯等,不太好理解,但是他的实用性是毋庸置疑的,所以即使这个算法再难,我们还是要试着去学习他,今天我们就硬着头皮来看一看这个DFS到底是何方神圣,到底有没有我们想的那么难。
DFS就是深度优先遍历算法,
大概的访问过程就是:
访问指定的起始顶点;
若当前访问的顶点的邻接顶点有未被访问的,则任选一个访问之;反之,退回到最近访问过的顶点;直到与起始顶点相通的全部顶点都访问完毕;
若此时图中尚有顶点未被访问,则再选其中一个顶点作为起始顶点并访问之,转 2; 反之,遍历结束。
接下来用一个动图来形象的描述一下DFS的过程
大家仔细的看一下这就是他的大致过程,好好理解一下DFS的过程,只要我们能把他的原理搞清楚,知道他的过程是什么样的,那么基本上我们也就真正的掌握了DFS了,
下面我们再把DFS的过程一步一步的走下去,我们再用图来具体的描述一下:
优先遍历,否则继续检查下一顶点。
访问指定的起始顶点;若当前访问的顶点的邻接顶点有未被访问的,则任选一个访问之;
反之,退回到最近访问过的顶点;直到与起始顶点相通的全部顶点都访问完毕;
回退到1,发现了新的没有被访问的结点
继续回退,回退到0
再也找不到新的结点了,那么回退,回退到起始顶点,结束搜索
顶点的访问序列为: v0 , v1 , v4 , v5 , v6 , v2 , v3(不唯一),
我先来大致上说一下我的理解,就是首先从一个点往下走,走啊走,走不动的时时候开始往回走,走到上一个节点之后就接着往下走,直到走不动的时候再返回往回走,以此类推,直到把所有的节点全部访问到,那么这个递归就结束了,
我们在这里只是简单的把原理理一下,要想真正的掌握它,还是要多刷题,下面给一道例题,来具体写一下代码:
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.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)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 0Sample Output
45 59 6 13
#include<stdio.h> #include<string.h> const int maxn=320; char ch[maxn][maxn]; int dis[maxn][maxn]; int n,m; int d[4][2]={1,0,-1,0,0,1,0,-1};//从每一个点能走的几个方向: int D(int x,int y) { if(x>=0&&x<n&&y>=0&&y<m&&dis[x][y]==0&&ch[x][y]!='#') return 1; return 0; } int cnt=0; void dfs(int x,int y) { if(D(x,y)==0) return ;//如果走不动的话,那么就返回,开始往回走; cnt++; dis[x][y]=1; for(int i=0;i<4;i++)//每一个点能走的四个方向: { int xx=x+d[i][0]; int yy=y+d[i][1]; dfs(xx,yy);//如果能走的话,那么就接着走·; } } int main() { while(~scanf("%d %d",&m,&n)&&(m||n)) { int x1,y1; cnt=0; memset(dis,0,sizeof(dis)); for(int i=0;i<n;i++) scanf("%s",ch[i]); for(int i=0;i<n;i++) { for(int j=0;j<m;j++) { if(ch[i][j]=='@') { x1=i;y1=j;break; } } } dfs(x1,y1); printf("%d\n",cnt); } return 0; }