这几天看深搜一直纠结
函数里面for循环递归,那分出去的分支是先进行一个还是同时进行,彼此之间有没有影响?
答案应该是先进行一个 而且有影响。
以此题为例(poj3278)
Red and Black
Time Limit: 1000 ms / Memory Limit: 32768 kb
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.
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).
#include <cstdio>
#include <iostream>
#include <string>
using namespace std;
int black=0;
int n, k;
char str[25][25];
int dir[4][2] = { 1,0,0,-1,0,1,-1,0 };
int step=0;
void bfs(int x,int y)
{
int i, j;
int xx, yy;
for (i = 0;i < k;++i)
{
for (j = 0;j < n;++j)
{
printf("%c", str[i][j]);
}
printf("\n");
}
for (i = 0;i < 4;++i)
{
xx = x + dir[i][0];
yy = y + dir[i][1];
if (xx >= 0 && yy >= 0 && xx < k&&yy < n &&str[xx][yy] == '.')
{
str[xx][yy] = '#';
black++;
step += 3 - i;
bfs(xx, yy);
}
else
printf("false%d\n",step);
}
}
int main(void)
{
while (scanf("%d%d", &n, &k) != EOF)
{
if (n == 0 && k == 0)
break;
memset(str, 0, sizeof(str));
int i, j;
int dx, dy;
for (i = 0;i < k;++i)
{
getchar();
for (j = 0;j < n;++j)
{
scanf("%c", &str[i][j]);
}
}
for (i = 0;i < k;++i)
{
for (j = 0;j < n;++j)
{
if (str[i][j] == '@')
{
dx = i;
dy = j;
}
}
}
str[dx][dy] = '#';
black++;
bfs(dx, dy);
cout << black << endl;
black = 0;
}
}
以下面为例,可见先是找到一个可行的点一直继续下去,如果走不动就输出false,(以下、左、右、上的顺序进行)直到最后输出了15个false,因为最后一个点是4个false,所以是先一条路走下去,然后反过头来继续前面的循环,因为数组已经变化了,所以都是false,输出了11个,这里可用定义的变量step证明。
3 3
@..
...
...
#..
...
...
#..
#..
...
#..
#..
#..
false6
false6
#..
#..
##.
false7
false7
#..
#..
###
false8
false8
false8
#..
#.#
###
false8
#..
###
###
false10
false10
false10
##.
###
###
false10
false10
###
###
###
false11
false11
false11
false11
false11
false11
false11
false11
false11
false11
false11
false11
false11
false11
false11
9
而如何遍历所有的可能走法呢?
bfs(xx,yy)后把str[xx][yy]='.'就可以了。
Ep:
2 2
@...
#.
..
#.
#.
false3
false3
#.
##
false4
false4
false4
##
##
false4
false4
false4
false4
false4
false4
##
..
##
.#
false8
##
##
false10
false10
false10
false10
false10
false10
false10
false10
false10
false10
7