Description
在H*W的房间中全部铺上了黑色或者白色的方形瓷砖,现在zser站在黑色的瓷砖上,他可以上下左右移动,但不能踏上红色的瓷砖。
现在你应统计zser能行走的瓷砖数目
Input
对于每组测试用例:
第一行输入W,H(1 <= H, W <= 20)
接下来输入H行,每行W个字符
其中:
'.'代表黑色瓷砖
'#'表示红色瓷砖
'@'表示zser所占的位置
输入的结尾由一个由2个0构成的行表示
Sample Input Copy
6 9
…#.
…#
…
…
…
…
…
#@…#
.#…#.
11 9
.#…
.#.#######.
.#.#…#.
.#.#.###.#.
.#.#…@#.#.
.#.#####.#.
.#…#.
.#########.
…
11 6
…#…#…#…
…#…#…#…
…#…#…###
…#…#…#@.
…#…#…#…
…#…#…#…
7 7
…#.#…
…#.#…
###.###
…@…
###.###
…#.#…
…#.#…
0 0
Sample Output Copy
45
59
6
13
代码实现
#include<bits/stdc++.h>
using namespace std;
#define ios ios::sync_with_stdio(false); cin.tie(NULL);
//const int N = 50010;
int n;
int m;
int ans;
char mp[25][25];
struct node
{
int a,b;
}str;
int fx[] = {0,1,0,-1};
int fy[] = {-1,0,1,0};
bool vis[25][25];
bool check(int x,int y)
{
if(x>=1&&x<=m&&y>=1&&y<=n&&!vis[x][y]&&mp[x][y]!='#')
return true;
return false;
}
void dfs(int x,int y)
{
ans++;
vis[x][y] = true;//每一次进入循环的都是可以走的点
for(int i=0; i<4; i++)
{
str.a = x+fx[i];
str.b = y+fy[i];
if(check(str.a,str.b))
{
dfs(str.a,str.b);
vis[str.a][str.b] = true;
}
}
}
int main()
{
while(cin>>n>>m)
{
if(n==0&&m==0)
break;
ans=0;
memset(vis,false,sizeof(vis));
for(int i=1; i<=m; i++)
{
for(int j=1; j<=n; j++)
{
cin>>mp[i][j];
if(mp[i][j]=='@')
{
str.a = i;
str.b = j;
}
}
}
dfs(str.a,str.b);
cout<<ans<<endl;
}
return 0;
}