DFS(深度优先搜索)
深度优先搜索是一种在开发爬虫早期使用较多的方法。它的目的是要达到被搜索结构的叶结点(即那些不包含任何超链的HTML文件) 。在一个HTML文件中,当一个超链被选择后,被链接的HTML文件将执行深度优先搜索,即在搜索其余的超链结果之前必须先完整地搜索单独的一条链。深度优先搜索沿着HTML文件上的超链走到不能再深入为止,然后返回到某一个HTML文件,再继续选择该HTML文件中的其他超链。当不再有其他超链可选择时,说明搜索已经结束。
基本思路
深度优先遍历图的方法是,从图中某顶点v出发:
(1)访问顶点v;
(2)依次从v的未被访问的邻接点出发,对图进行深度优先遍历;直至图中和v有路径相通的顶点都被访问;
(3)若此时图中尚有顶点未被访问,则从一个未被访问的顶点出发,重新进行深度优先遍历,直到图中所有顶点均被访问过为止。 当然,当人们刚刚掌握深度优先搜索的时候常常用它来走迷宫.事实上我们还有别的方法,那就是广度优先搜索(BFS).
代码示例
int ans,sx,sy,W,H;
int dx[4]={0,0,1,-1};
int dy[4]={1,-1,0,0};
void dfs(int x,int y){
for(int i=0;i<=3;i++){
int tx=x+dx[i],ty=y+dy[i];
if(a[tx][ty]=='#'){
a[tx][ty]='.';
dfs(tx,ty);
}
}
}
题目示例
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 0
Sample Output
45
59
6
13
代码示例
#include <cstdio>
#include <cstdlib>
#include <algorithm>
#include <iostream>
#include <cstring>
#include <string>
#include <cmath>
using namespace std;
int w,h,sx,sy,ans;
char map[21][21];//元素容器
int dx[4]={0,0,1,-1};//上下左右移动
int dy[4]={1,-1,0,0};
bool v[21][21];//检测单元格是否已经检测过
void dfs(int x,int y)//DFS深度优先搜索算法
{
for(int i=0;i<=3;i++)
{
int tx=x+dx[i],ty=y+dy[i];//上下左右的坐标位置
if(tx>=1&&tx<=h&&ty>=1&&ty<=w&&map[tx][ty]!='#'&&v[tx][ty]==0)//判断是否为目标元素
{
ans++;//结果数增加
v[tx][ty]=1;//标记目标单元格已被检测
dfs(tx,ty);//迭代进行剩下位置的dfs
}
}
}
int main()//主函数
{
while(cin>>w>>h&&w!=0&&h!=0)//输入w,h值
{
ans=0;//初始化
for(int i=1;i<=h;i++)
for(int j=1;j<=w;j++)
{
cin>>map[i][j];
if(map[i][j]=='@')//找到人所在位置
{
sx=i;
sy=j;
}
}
memset(v,0,sizeof(v));//初始化
v[sx][sy]=1;//标记目标单元格已被检测
dfs(sx,sy);//引用dfs查找
cout<<ans+1<<endl;//输出
}
return 0;
}