红与黑 题解
红与黑
有一间长方形的房子,地上铺了红色、黑色两种颜色的正方形瓷砖。你站在其中一块黑色的瓷砖上,只能向相邻的黑色瓷砖移动。请写一个程序,计算你总共能够到达多少块黑色的瓷砖。
Input包括多个数据集合。每个数据集合的第一行是两个整数W和H,分别表示x方向和y方向瓷砖的数量。W和H都不超过20。在接下来的H行中,每行包括W个字符。每个字符表示一块瓷砖的颜色,规则如下
1)‘.’:黑色的瓷砖;
2)‘#’:白色的瓷砖;
3)‘@’:黑色的瓷砖,并且你站在这块瓷砖上。该字符在每个数据集合中唯一出现一次。
当在一行中读入的是两个零时,表示输入结束。
Output对每个数据集合,分别输出一行,显示你从初始位置出发能到达的瓷砖数(记数时包括初始位置的瓷砖)。
Sample Input
6 9 ....#. .....# ...... ...... ...... ...... ...... #@...# .#..#. 0 0
Sample Output
45
PS:这个题唯一的关键点就在bfs函数的中止条件,其实就是棋盘的边界条件辣哈哈hh~~,详情见代码咯~~
#include<stdio.h>
#include<iostream>
#include<queue>
#include<cstring>
#define N 25
using namespace std;
char mp[N][N];
int r,c,vis[N][N],cnt;
int fx[4]={1,0,-1,0};
int fy[4]={0,1,0,-1};
struct node
{
int x,y;
}s,now,nxt;
bool check(int x,int y)
{
if(!vis[x][y] && mp[x][y]=='.' && x>=0 && x<r && y>=0 && y<c)
return 1;
return 0;
}
void bfs()
{
queue<node> q;
q.push(s);
while(q.size())
{
now=q.front();
q.pop();
if(now.x<0 || now.x>=r || now.y<0 || now.y>=c) break;
//在 now 这里判断
for(int i=0;i<4;i++)
{
nxt.x = now.x+fx[i];//now.x替换了x
nxt.y = now.y+fy[i];
if(check(nxt.x,nxt.y))
{
cnt++;
vis[nxt.x][nxt.y]=1;
q.push(nxt);
// printf("san %d %d %c %d %d\n",next.x,next.y,mp[next.x][next.y],i,cnt);
}
}
}
return ;
}
int main()
{
while(cin>>c>>r && r+c)
{
cnt=1;
memset(vis,0,sizeof vis);
memset(mp,0,sizeof mp);
for(int i=0;i<r;i++)
{
for(int j=0;j<c;j++)
{
cin>>mp[i][j];
if(mp[i][j]=='@')
{
s.x=i;
s.y=j;
}
}
}
// for(int j=0;j<r;j++)
// {
// for(int k=0;k<c;k++)
// {
// printf("yi--%d %d %c ",j,k,mp[j][k]);
// //打印所有可走的点
// }
// printf("\n");
// }
bfs();
cout<<cnt<<endl;
}
return 0;
}