黑红砖块,POJ-1979,BFS

题目的

".'' - 黑色瓷砖
'#' - 红色瓷砖
'@' - 黑色瓷砖上的男人(在数据集中只显示一次)

这间长方形客房铺有方形瓷砖。每个瓷砖都是红色或黑色。一个男人站在黑色的瓷砖上。从瓷砖中,他可以移动到四个相邻瓷砖中的一个。但是他不能在红色瓷砖上移动,他只能在黑色瓷砖上移动。

编写一个程序,通过重复上述动作来计算他可以达到的黑色瓷砖的数量。

就是计算他能 到达“.”的数量,包括最开始他站的点;

#include <iostream>
#include<stdio.h>
#include<string.h> 
#include<queue>
using namespace std;
int m,n;
int sx,sy;
 
char map[25][25];
int vis[25][25];
int to[4][2]={{1,0},{-1,0},{0,1},{0,-1}};
struct node{
	int x,y;
}now,next;
void bfs(int xx,int yy){
	queue<node> q;
	int ans=0;
	now.x=xx;
	now.y=yy;
	q.push(now);
	while(!q.empty()){
		now=q.front();
		q.pop();
		for(int i=0;i<4;i++)
		{
			next.x=now.x+to[i][0];
			next.y=now.y+to[i][1];
			if(next.x>=1&&next.y>=1&&next.x<=m&&next.y<=n&&!vis[next.x][next.y]&&map[next.x][next.y]=='.')
			{
				vis[next.x][next.y]=1;
				ans++;
				q.push(next);
			}
		}
	}
	cout<<ans+1<<endl;
	
}
int main(){
	while(scanf("%d%d",&n,&m),n+m)
	{
		memset(map,'\0',sizeof(map));
		memset(vis,0,sizeof(vis));
		for(int i=1;i<=m;i++)
		for(int j=1;j<=n;j++)
		{
			cin>>map[i][j];
			if(map[i][j]=='@')
			{
				sx=i;
				sy=j;
			}
		}
		bfs(sx,sy);
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/Harington/article/details/81974335