原题再现
描述
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.
输入
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.
输出
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).
样例输入
6 9
....#.
.....#
......
......
......
......
......
#@...#
.#..#.
11 9
.#.........
.#.#######.
.#.#.....#.
.#.#.###.#.
.#.#..@#.#.
.#.#####.#.
.#.......#.
.#########.
...........
11 6
..#..#..#..
..#..#..#..
..#..#..###
..#..#..#@.
..#..#..#..
..#..#..#..
7 7
..#.#..
..#.#..
###.###
...@...
###.###
..#.#..
..#.#..
0 0
45 59 6 13
题目大意
从 @ 处出发,统计能踩到的.块的个数。
大体思路
使用递归解决。
假设当前处在(xf,yf)点处,判断该点的上下左右是否可踩(可踩即为 . 块)。
假设(xf,yf)点的上方为 . 块,则递归判断(xf,yf - 1)点
假设(xf,yf)点的下方为 . 块,则递归判断(xf,yf +1)点
假设(xf,yf)点的左方为 . 块,则递归判断(xf - 1,yf )点
假设(xf,yf)点的右方为 . 块,则递归判断(xf +1,yf )点
每次踩过一块砖后,counter自增,同时还需要将此处标记(代码中是标记为 ‘T’),以防重复计数。
#include <iostream>
using namespace std;
int x=0,y=0;
char map[20][20];
int cover;
void solve(int xf,int yf)
{
cover++;
map[xf][yf]='T';
if(xf>=1&&map[xf-1][yf]=='.') {
solve(xf-1,yf);
}
if(xf<=x-2&&map[xf+1][yf]=='.') {
solve(xf+1,yf);
}
if(yf>=1&&map[xf][yf-1]=='.') {
solve(xf,yf-1);
}
if(yf<=y-2&&map[xf][yf+1]=='.') {
solve(xf,yf+1);
}
return ;
}
int main()
{
int xat=-1,yat=-1;
while(cin>>y>>x) {
if(x==0&&y==0){
break;
}
for(int i=0; i<=x-1; i++) {
for(int j=0; j<=y-1; j++) {
cin>>map[i][j];
if(map[i][j]=='@') {
xat=i;
yat=j;
}
}
}
cover=0;
solve(xat,yat);
cout<<cover<<endl;
}
return 0;
}