Red and Black(搜索题目)

来源:互联网 发布:八爪鱼采集软件免费版 编辑:程序博客网 时间:2024/06/05 09:08
Red and Black
Time Limit: 1000MS Memory Limit: 32768KB64bit 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
45
59
6
13 
 
Source

Asia 2004, Ehime (Japan), Japan Domestic

简单的搜索问题,根据题意,可以重复行走,求能到达的最多的...的数量,刚开始拿过题来以为是宽搜,因为做了几个宽搜的题目,形成思维定视了,后来一看到重复行走就想到了深搜。

#include <cstdio>#include <iostream>#include <cmath>#include <queue>#include <algorithm>using namespace std;int dx[4]={-1,0,1,0};int dy[4]={0,-1,0,1};int map[40][40];int m,n;struct node{    int x;    int y;    int sept;};int sum;int bfs(int a,int b){    if (map[a][b]=='.')    {        map[a][b]='&';        sum++;    }    for (int number1=0;number1<4;number1++)    {        int nx=a+dx[number1],ny=b+dy[number1];        if (map[nx][ny]=='.'&&nx>=0&&nx<n&&ny>=0&&ny<m)        {            bfs(nx,ny);        }    }}int main(){    while(scanf("%d %d",&m,&n)!=EOF)    {        if (m==0&&n==0)break;        int i,j;        getchar();        for (int number1=0;number1<n;number1++)        {            for (int number2=0;number2<m;number2++)            {                scanf("%c",&map[number1][number2]);                if (map[number1][number2]=='@')                {                    i=number1;                    j=number2;                }            }            getchar();        }        sum=1;        bfs(i,j);        printf("%d\n",sum);    }    return 0;}



0 0
原创粉丝点击