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:
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:
题目大意:
给出一张图,图上面有黑砖"."与红砖“#”与初始点“@”,红砖是不能踩的,只有黑砖和初始点才能踩,然后问你在这张图怎么走,才能走的最多黑砖,初始点也是黑砖,所以这也要记录。
思路分析:
这道题直接从初始点“@”开始DFS,然后每次所走的路线记录最多黑砖数量,然后在输出就行了。
AC代码:
用时:15ms
#include<cstdio>
#include<string.h>
int x,y;//地图的行数与列数
char c1[22][22];//记录地图
int c2[22][22];//标记所走的位置是否走过
int x1,y1,max;//x1与y1为初始点@的位置,max为黑砖最大数量。
int div[4][4]={{1,0},{0,1},{-1,0},{0,-1}};//方向分别为上下左右
int n;
void LemonScanf()
{
int d,e;
for(d=0;d<x;d++)
{
scanf("%s",c1[d]);
}
for(d=0;d<x;d++)
{
for(e=0;e<y;e++)
{
if(c1[d][e]=='@')
{
x1=d;
y1=e;
}
}
}
}
void LemonDFS(int x1,int y1)
{
int i;
if(n>max)//比较数量
{
max=n;
}
for(i=0;i<4;i++)
{
int x2=x1+div[i][0];
int y2=y1+div[i][1];
if(x2<0 || y2<0 || x2>=x || y2>=y || c1[x2][y2]=='#' || c2[x2][y2])
//判断是否越界与是否是红砖与是否走过该位置
continue;
if(c1[x2][y2]=='.')
{
n++;//记录所踩黑砖数量
c2[x2][y2]=1;//标记该位置
LemonDFS(x2,y2);//继续深搜
}
}
return;
}
int main()
{
while(scanf("%d %d",&y,&x)!=EOF)
{
max=0;
n=1;
if(x==0&&y==0)break;
memset(c2,0,sizeof(c2));//这里是为了刷新c2的数据,防止对后面测试组造成错乱
LemonScanf();
LemonDFS(x1,y1);
printf("%d\n",max);//输出最大黑砖数量
}
}