一般来说,广搜常用于找单一的最短路线,或者是规模小的路径搜索,它的特点是"搜到就是最优解", 而深搜用于找多个解或者是"步数已知(好比3步就必需达到前提)"的标题,它的空间效率高,然则找到的不必定是最优解,必需记实并完成全数搜索,故一般情况下,深搜需要很是高效的剪枝(优化).(剪枝真真的要命啊)
像搜索最短路径这些的很显著若是用广搜,因为广搜的特征就是一层一层往下搜的,保证当前搜到的都是最优解,当然,最短路径只是一方面的操作,像什么起码状态转换也是可以操作的。
深搜就是优先搜索一棵子树,然后是另一棵,它和广搜对比,有着内存需要相对较少的所长,八皇后标题就是典范楷模的操作,这类标题很显著是不能用广搜往解决的。或者像图论里面的找圈的算法,数的前序中序后序遍历等,都是深搜。下面就拿出一道深搜的题目练练手。
Red and Black
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)Total Submission(s): 10104 Accepted Submission(s): 6301
Problem 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>
int dir[4][2]={{1,0},{-1,0},{0,1},{0,-1}};//四个方向
int m,n,bx,by,cnt;
char map[22][22];
void dfs(int x,int y)//深搜求所有符合要求的点
{
int i;cnt++;
for(i=0;i<4;i++)
{
int fx=x+dir[i][0];
int fy=y+dir[i][1];
if(fx>=0&&fx<n&&fy>=0&&fy<m&&map[fx][fy]=='.')
{
map[fx][fy]='#' ;//找到一个黑块标记一下下次不可以再走
dfs(fx,fy);
}
}
}
int main()
{
int i,j;
//freopen("int.txt","r",stdin);
while(scanf("%d%d",&m,&n)!=EOF)
{
getchar();
if(m==0&&n==0)break;
for(i=0;i<n;i++)
{
for(j=0;j<m;j++)
{
scanf("%c",&map[i][j]);
if(map[i][j]=='@'){bx=i;by=j;}
}
getchar();
}
cnt=0;map[bx][by]='#';
dfs(bx,by);
printf("%d\n",cnt);
}
return 0;
}
一遍ac是不是很爽啊~那么我要找一点有难度的搜索喽