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
Source
有一間長方形的房子,地上鋪了紅色、黑色兩種顏色的正方形瓷磚。你站在其中一塊黑色的瓷磚上,只能向相鄰的黑色瓷磚移動。請寫一個程序,計算你總共能夠到達多少塊黑色的瓷磚。
Input
包括多個數據集合。每個數據集合的第一行是兩個整數W和H,分別表示x方向和y方向瓷磚的數量。W和H都不超過20。在接下來的H行中,每行包括W個字符。每個字符表示一塊瓷磚的顏色,規則如下
1)‘.’:黑色的瓷磚;
2)‘#’:白色的瓷磚;
3)‘@’:黑色的瓷磚,並且你站在這塊瓷磚上。該字符在每個數據集合中唯一出現一次。
當在一行中讀入的是兩個零時,表示輸入結束。
Output
對每個數據集合,分別輸出一行,顯示你從初始位置出發能到達的瓷磚數(記數時包括初始位置的瓷磚)。
Sample Input
6 9 ....#. .....# ...... ...... ...... ...... ...... #@...# .#..#. 0 0
Sample Output
45
這個利用計算機的遞歸思想。
以上爲例。由當前所在的位置,上下左右四個方向依次序搜索。
#include<iostream>
#include<string.h>
using namespace std;
#define N 100
#define B 1
#define W 2
#define P 3
int flag[N][N];
int floor[N][N];
int w,h;
int canPos(int i,int j){
if(flag[i][j] == 1)
return false;
if(floor[i][j] == W)
return false;
if(i<0||i>=h||j<0||j>=w)
return false;
return true;
}
void dfs(int i,int j,int &count){
if(canPos(i,j) == false)
return ;
flag[i][j] = 1;
count++;
dfs(i+1,j,count);
dfs(i,j+1,count);
dfs(i-1,j,count);
dfs(i,j-1,count);
}
int main()
{
while(cin>>w&&cin>>h&&(w||h)){
memset(flag,0,N*N*sizeof(int));
memset(floor,0,N*N*sizeof(int));
int m,n;
for(int i=0;i<h;i++){
for(int j=0;j<w;j++){
char ch;
cin>>ch;
switch(ch){
case '.':
floor[i][j] = B;
break;
case '#':
floor[i][j] = W;
break;
case '@':
floor[i][j] = P;
m = i;
n = j;
break;
default:
return -1;
}
}
}
int count = 0;
dfs(m,n,count);
cout<<count<<endl;
}
return 0;
}