其實吧!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; }