poj 1979 Red and Black

Red and Black
Time Limit: 1000MS   Memory Limit: 30000K
Total Submissions: 25228   Accepted: 13605

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) 
The end of the input is indicated by a line consisting of two zeros. 

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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
/*
题意:给你一个n*m的矩阵,字符@是起点字符.是路字符#是墙,问你
从起点开始最多可以走多长的路(即可以走过多少个点,注意:墙不可穿过)
题解:找到起点的坐标,然后向它的四个方向搜索,找到所有的可以走的路
每走过一个点,就在总路数上+1(同样注意将走过的路用#覆盖,避免重复)
*/
 
#include<stdio.h> //poj1979
#include<string.h>
#include<algorithm>
#define MAX 110
#define INF 0x3f3f3f
using namespace std;
int n,m,j,i,t,k;
int sum;
char map[MAX][MAX];
int vis[MAX][MAX];
//int move[4][2]={1,0,-1,0,0,-1,0,1};
//此题不能用这个辅助数组,因为这个辅助数组走一步之后起点的
//(x,y)的坐标发生了变化,而走过的路已经被覆盖,导致无法再走
void dfs(int x,int y)
{
    if(0<=x&&x<m&&0<=y&&y<n&&map[x][y]!='#')
    {
        map[x][y]='#';
        sum++;
        dfs(x+1,y);
        dfs(x-1,y);
        dfs(x,y-1);
        dfs(x,y+1);
        //这样搜索,由于搜索一次后(x,y)并没有改变就不会有上边的问题
//      for(i=0;i<4;i++)
//          dfs(x+move[i][0],y+move[i][1]);
    }
    return ;
}
int main()
{
    int x,y;
    while(scanf("%d%d",&n,&m),n|m)
    {
        sum=0;
        for(i=0;i<m;i++)
            scanf("%s",map[i]);
        for(i=0;i<m;i++)
            for(j=0;j<n;j++)        
                if(map[i][j]=='@')//找到起点坐标并记录下来
                {
                    x=i;
                    y=j;
                }
        dfs(x,y);
        printf("%d\n",sum);
    }
    return 0;
}

  

  




posted @   非我非非我  阅读(149)  评论(0编辑  收藏  举报
点击右上角即可分享
微信分享提示