有一间长方形的房子,地上铺了红色、黑色两种颜色的正方形瓷砖。
你站在其中一块黑色的瓷砖上,只能向相邻(上下左右四个方向)的黑色瓷砖移动。
请写一个程序,计算你总共能够到达多少块黑色的瓷砖。
输入格式
输入包括多个数据集合。
每个数据集合的第一行是两个整数 W 和 H,分别表示 x 方向和 y 方向瓷砖的数量。
在接下来的 H 行中,每行包括 W 个字符。每个字符表示一块瓷砖的颜色,规则如下
1)‘.’:黑色的瓷砖;
2)‘#’:红色的瓷砖;
3)‘@’:黑色的瓷砖,并且你站在这块瓷砖上。该字符在每个数据集合中唯一出现一次。
当在一行中读入的是两个零时,表示输入结束。
输出格式
对每个数据集合,分别输出一行,显示你从初始位置出发能到达的瓷砖数(记数时包括初始位置的瓷砖)。
数据范围
1≤W,H≤20
输入样例:
6 9
…#.
…#
…
…
…
…
…
#@…#
.#…#.
0 0
输出样例:
45
#include <iostream>
#include <cstring>
#include <algorithm>
#include <queue>
using namespace std;
const int N = 25;
char g[N][N];
bool vis[N][N];
struct node
{
int x,y;
};
int nextt[4][2] = {{0,1},{0,-1},{1,0},{-1,0}};
int main()
{
int w,h;
while(cin>>w>>h){
if(w==0 && h==0) break;
for(int i=0; i<h; ++i)
cin>>g[i];
memset(vis,0,sizeof vis);
queue<node> q;
node st;
for(int i=0; i<h; ++i){
for(int j=0; j<w; ++j)
{
if(g[i][j]=='@'){
st.x = i,st.y = j;
break;
}
}
}
q.push({st.x,st.y});
vis[st.x][st.y] = true;
int ans = 1;
while(!q.empty())
{
int len = q.size();
while(len--){
node tmp = q.front();
q.pop();
for(int i=0; i<4; ++i){
int tx = tmp.x + nextt[i][0];
int ty = tmp.y + nextt[i][1];
if(tx<0||tx>=h||ty<0||ty>=w) continue;
if(!vis[tx][ty] && g[tx][ty]!='#'){
q.push({tx,ty});
vis[tx][ty] = true;
ans++;
}
}
}
}
cout<<ans<<endl;
}
return 0;
}