【搜索-DFS】Red and Black

来源:互联网 发布:脸型与眉毛软件 编辑:程序博客网 时间:2024/05/19 13:18

Red and Black
Time Limit:1000MS     Memory Limit:32768KB     64bit IO Format:%I64d & %I64u
Submit Status

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).
 

Sample Input

6 9....#......#..............................#@...#.#..#.11 9.#..........#.#######..#.#.....#..#.#.###.#..#.#..@#.#..#.#####.#..#.......#..#########............11 6..#..#..#....#..#..#....#..#..###..#..#..#@...#..#..#....#..#..#..7 7..#.#....#.#..###.###...@...###.###..#.#....#.#..0 0
 

Sample Output

4559613

也是一道简单题目,用DFS做。这题让我更加理解了DFS,原来使用DFS可以将整个迷宫的每个角落都搜到。与搜索迷宫方法不同的一点就是搜索迷宫要标记走过了的地方,回溯时再解除标记,而搜完迷宫每个角落则不需要解除标记……最开始我做的时候将递归弄成了死循环,原因是每走一个方块我将其变成“#”,递归完后又还原,就是没弄清楚差别

代码如下:

#include<stdio.h>#include<iostream>#include<string.h>#include<algorithm>#include<math.h>using namespace std;int sum,dir[4][2]={0,-1,-1,0,0,1,1,0},flag[23][23];char map[23][23];void dfs(int x,int y){    map[x][y]='#';    flag[x][y]=1;    for(int i=0;i<4;i++)    {        int xx=x+dir[i][0];int yy=y+dir[i][1];        if(map[xx][yy]=='#'||flag[xx][yy]==1)        continue;        sum++;        dfs(xx,yy);    }    map[x][y]='.';}int main(){    int r,c,i,j,x,y;    while(~scanf("%d%d",&c,&r))    {        if(c==0&&r==0)        break;        sum=1;        memset(map,'#',sizeof(map));        memset(flag,0,sizeof(flag));        for(i=1;i<=r;i++)        {            getchar();            for(j=1;j<=c;j++)           {              scanf("%c",&map[i][j]);              if(map[i][j]=='@')              {                  x=i;y=j;              }           }        }        dfs(x,y);        cout<<sum<<endl;    }    return 0;}

0 0