POJ1979—http://poj.org/problem?id=1979
题目描述
有一间长方形的房子,地上铺了红色、黑色两种颜色的正方形瓷砖。你站在其中一块黑色的瓷砖上,只能向相邻的黑色瓷砖移动。请写一个程序,计算你总共能够到达多少块黑色的瓷砖。
输入
包括多个数据集合。每个数据集合的第一行是两个整数W和H,分别表示x方向和y方向瓷砖的数量。W和H都不超过20。在接下来的H行中,每行包括W个字符。每个字符表示一块瓷砖的颜色,规则如下:
1)‘.’:黑色的瓷砖;
2)‘#’:白色的瓷砖;
3)‘@’:黑色的瓷砖,并且你站在这块瓷砖上。该字符在每个数据集合中唯一出现一次。
当在一行中读入的是两个零时,表示输入结束。
输出
对每个数据集合,分别输出一行,显示你从初始位置出发能到达的瓷砖数(记数时包括初始位置的瓷砖)。
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
//
#include<bits/stdc++.h>//C++的万能头文件
using namespace std;
int mmap[21][21];//存能不能走
int book[21][21];//标记是不是走过
int dx[4]={-1,0,1,0};//x的移动方向
int dy[4]={0,1,0,-1};//y的移动方向
int sx,sy;
int m,n,num;
void dfs(int x,int y){//搜索x,y的上下左右能不能走
int xx,yy;
for(int i=0;i<4;i++){
xx=x+dx[i];//数组表示移动方向
yy=y+dy[i];
if(book[xx][yy]==0&&mmap[xx][yy]==1&&xx>0&&xx<=n&&yy>0&&yy<=m){//x,y不能越界
book[xx][yy]=1; //搜索过就标记一下
num++;
dfs(xx,yy); //继续搜索
}
}
return;
}
int main()
{
char ch;
while(cin>>m>>n){
if(m==0&&n==0) break;
memset(book,0,sizeof(book));//初始化两个数组
memset(mmap,0,sizeof(mmap));
for(int i=1;i<=n;i++){//注意m,n
for(int j=1;j<=m;j++){
cin>>ch;
if(ch=='.'){
mmap[i][j]=1;//1表示可以走
}
else if(ch=='#'){
mmap[i][j]=0;//0表示不能走
}
else if(ch=='@'){
mmap[i][j]=1;
sx=i;//记录开始坐标,
sy=j;
book[sx][sy]=1;//标记初始走过
num=1;//num表示能走的瓷砖块数
}
}
}
dfs(sx,sy);//进行dfs搜索,广度
cout<<num<<endl;
}
return 0;
}