Red and Black
题目描述:
There is a rectangular room, covered with square tiles. Each tile is colored either red or black. A man is standing on a black tile. From a tile, he can move to one of four adjacent tiles. But he can’t move on red tiles, he can move only on black tiles.
Write a program to count the number of black tiles which he can reach by repeating the moves described above.
Input:
Input
The input consists of multiple data sets. A data set starts with a line containing two positive integers W and H; W and H are the numbers of tiles in the x- and y- directions, respectively. W and H are not more than 20.
There are H more lines in the data set, each of which includes W characters. Each character represents the color of a tile as follows.
‘.’ - a black tile
‘#’ - a red tile
‘@’ - a man on a black tile(appears exactly once in a data set)
Output:
For each data set, your program should output a line which contains the number of tiles he can reach from the initial tile (including itself).
Sample Input:
Sample Output:
题目大意:
就是给出一个地图,图上有红砖和黑砖以及一个初始点,分别为“#”与“.“与”@“,并且红砖不能踩,问你从初始点开始走,问最多能踩多少黑砖。
思路分析:
这道题直接用BFS套模版进去,用整数数组标记位置是否走过即可,BFS和DFS,没想到BFS的时间居然只要0ms真的很块,但是空间郁闷了。
AC代码:
用时:0MS
#include<cstdio>
#include<iostream>
#include<cstring>
#include<algorithm>
#include<queue>
using namespace std;
struct num1//创建数据结构
{
int x;
int y;
int num;
};
int LemonJudge(int x2,int y2);
char c1[22][22];//构造地图
int vis[22][22];//标记位置是否走过
int b,c;//地图的行与列
int x1,y1;//初始的位置
int sum;//黑砖数量
int die[5][2]={{1,0},{0,1},{-1,0},{0,-1}};//方向变量
void LemonScanf()//输入地图
{
int d,e;
for(d=0;d<c;d++)
{
scanf("%s",c1[d]);
}
for(d=0;d<c;d++)
{
for(e=0;e<b;e++)
{
if(c1[d][e]=='@')//找初始点
{
x1=d;
y1=e;
break;
}
}
}
}
int LemonJudge(int x2,int y2)
{
if(x2<0 || y2<0 || x2>=c || y2>=b || c1[x2][y2]=='#' || vis[x2][y2])
{
return 1;
}
return 0;
}
void LemonBFS()
{
num1 next,Lemon;
int i;
Lemon.x=x1;//记录第一个点
Lemon.y=y1;//记录第一个点的纵坐标
queue<num1>q;//创造队列
q.push(Lemon);//将Lemon的数据结构放入队列中
vis[Lemon.x][Lemon.y]=1;//标记初始位置走过
while(!q.empty())//如果队列无元素,就结束循环
{
Lemon=q.front();//
q.pop();//删除顶元素
for(i=0;i<4;i++)
{
next.x=Lemon.x+die[i][0];//记录下一次的坐标
next.y=Lemon.y+die[i][1];
if(LemonJudge(next.x,next.y))//判断条件
{
continue;
}
vis[next.x][next.y]=1;//标记
sum++;
q.push(next);//将next数据结构放入新的队列中
}
}
}
int main()
{
while(scanf("%d %d",&b,&c)!=EOF)
{
if(b==0 && c==0)break;
memset(vis,0,sizeof(vis));
//刷新数据
sum=1;
LemonScanf();
LemonBFS();
printf("%d\n",sum);
}
}