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.
 

 

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
 
题意是:从@(本身算一个)开始找能够走通的‘。’有几个
思路:利用广度搜索法,先找其四周的位置是否为‘。’,如果是就先将他们的位置记录在数组中,并将该位置的记为‘#’,直到找完为止。
代码:

#include"iostream"
#define N 21
using namespace std;

typedef struct
{int x;
 int y;
}node;

node jilu[N*N];
char map[N][N];   //记录该图;
int s1,s2;        //记录起始位置;
int s;          //记录个数,起始点为1;
int star,end;
int fx[4][2]={{-1,0},{1,0},{0,-1},{0,1}};
int h,w;

void BB()
{
 s=1;
 star=0;
 end=1;
    node first,next;
    jilu[0].x=s1;
    jilu[0].y=s2;
 map[s1][s2] = '#';//本身就是一个可以的点(即s=1),要将它去掉(防止重复)
 while(end!=star)
 {
  first=jilu[star];
  star++;           //去掉头个;
  for(int i=0;i<4;i++)   //判断四个方位是否满足;
  {
   next.x=first.x+fx[i][0];
   next.y=first.y+fx[i][1];
   if(next.x>=0 && next.x<h && next.y>=0 && next.y<w && map[next.x][next.y]!='#')
   {
    s++;
    map[next.x][next.y] = '#';
    jilu[end]=next;
       end++;
   } 
  }
 }
 cout<<s<<endl;
}

int main()
{
 while(cin>>w>>h&&w&&h)
   {
 for(int j=0;j<h;j++ )
 {
  for(int k=0;k<w;k++)
  {
   cin>>map[j][k];
   if(map[j][k]=='@')
    s1=j,s2=k;
  }
 
 }
 BB();
   }
 return 0;

}

 
posted on 2012-05-23 22:46  xinmenghuairi  阅读(321)  评论(0编辑  收藏  举报