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.
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.
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
题目大意:
'.'——黑砖
'#'——红砖
'@'——男子
一个男子站在黑色的砖上,由此出发可以移到四个相邻的瓷砖上,但他不能一道红砖上,只能移到黑砖上。计算所能经过的黑砖数。
注意:
一个数据集开头包含两个正整数,分别表示矩形房间的列数和行数,而不是行数和列数。
试题解析
使用递归方法(回溯法)求解男子经过的瓷砖数。设n,m分别为矩形房间的行数和列数;ans为男子经过的瓷砖数,初始时为0;map为瓷砖图,其中map[i][j]为格点[i,j]的字符;visited为访问标志,其中visited[i][j]=true,表明男子已经过格点(i,j);递归过程为search(i,j)。其中,
状态:男子的当前位置(i,j)。显然递归前为出发位置。
边界条件:若当前格点在地图外(i<0||i>= n||j<0||j>=m),或不可通行(map[i][j] == '#'),或已经访问过(visited[i][j]==true),则回溯;否则为格点(i,j)设访问标志(visited[i][j]=true),男子经过的瓷砖数+1(++ans),继续递归。
搜索范围:递归(i,j)的四个相邻格点(search(i-1,j),search(i+1,j),search(i,j-1),search(i, j+1))。
#include <iostream>
using namespace std;
int n,m;
int sum;
char map[30][30];
bool ma[30][30];
int main()
{
int search(int ,int );
while(cin>>n>>m&&n||m)//n是列数,m是行数
{
memset(ma,false,sizeof(ma));
int i,j;
int a,b;//记录人的位置
for(i=0;i<m;i++)
for(j=0;j<n;j++)
{
cin>>map[i][j];
if(map[i][j]=='@')
{
a=i;//a记录行数
b=j;//b记录列数
}
}
sum=0;
search(a,b);
cout<<sum<<endl;
}
return 0;
}
int search(int a,int b)
{
if(a<0||a>=m||b<0||b>=n||map[a][b]=='#'||ma[a][b]!=0)
return 0;
ma[a][b]=true;
sum=sum+1;
search(a-1,b);
search(a+1,b);
search(a,b+1);
search(a,b-1);
}