红与黑

有一个矩形房间,覆盖正方形瓷砖。每块瓷砖涂成了红色或黑色。一名男子站在黑色的瓷砖上,由此出发,可以移到四个相邻瓷砖之一,但他不能移动到红砖上,只能移动到黑砖上。编写一个程序,计算他通过重复上述移动所能经过的黑砖数(一开始站立的黑砖也要算)。

输入

开头行包含两个正整数W和H,W和H分别表示矩形房间的列数和行数,且都不超过20.
每个数据集有H行,其中每行包含W个字符。每个字符的含义如下所示:

'.'——黑砖
'#'——红砖
'@'——男子(仅出现一次)

输出

程序应该输出一行,包含男子从初始瓷砖出发可到达的瓷砖数

样例输入

6 9
....#.
.....#
......
......
......
......
......
#@...#
.#..#.

样例输出

45



#include <bits/stdc++.h>
using namespace std;
char mapp[21][21];
int r,c,vis[21][21],cnt;
int a[4]={1,0,-1,0};
int b[4]={0,1,0,-1}; 
struct xyint
{
	int x,y;
}s;
queue<xyint> q;
void bfs()
{
	xyint now,nextt;
	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;
	for(int i=0;i<4;i++)
	{
	nextt.x = now.x+a[i], nextt.y = now.y+b[i];
	if(!vis[nextt.x][nextt.y] && mapp[nextt.x][nextt.y]=='.' && nextt.x>=0 && nextt.x<r && nextt.y>=0 && nextt.y<c)
	{
	cnt++;
	vis[nextt.x][nextt.y]=1;
	q.push(nextt);
	}
	} 
	}
}
int main()
{
	cin >> c >> r;
	cnt=1;
	for(int i=0;i<r;i++)
	{
	for(int j=0;j<c;j++)
	{
	cin >> mapp[i][j];
	if(mapp[i][j]=='@')
	{
	s.x=i;
	s.y=j;
	}
	}
	}
	bfs();
	cout<<cnt;
	return 0;
}
作者:Momo·Trace原文地址:https://www.cnblogs.com/momotrace/p/red-and-black.html

%s 个评论

要回复文章请先登录注册