POJ 1979 Red and Black (DFS)
2024-08-30 08:17:51
Description
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
6 9
....#.
.....#
......
......
......
......
......
#@...#
.#..#.
11 9
.#.........
.#.#######.
.#.#.....#.
.#.#.###.#.
.#.#..@#.#.
.#.#####.#.
.#.......#.
.#########.
...........
11 6
..#..#..#..
..#..#..#..
..#..#..###
..#..#..#@.
..#..#..#..
..#..#..#..
7 7
..#.#..
..#.#..
###.###
...@...
###.###
..#.#..
..#.#..
0 0
Sample Output
45
59
6
13
#include<cstdio>
#include<string.h>
int px[]={-,,,};
int py[]={,,-,};
int ans;
bool key[][];
char a[][];
int n,m,x,y;
void f(int x,int y)
{
int nx,ny;
for(int i = ;i < ; i++)
{
nx=x+px[i];
ny=y+py[i];
if(nx >= && ny >= && a[nx][ny] == '.' && key[nx][ny] == false && nx < m && ny < n)
{
ans++;
key[nx][ny]=true;
f(nx,ny);
}
}
}
int main()
{ while(scanf("%d %d",&n,&m) && n && m)
{
memset(key,false,sizeof(key));
for(int i = ; i < m ; i++)
{
getchar();
for(int j = ; j < n ; j++)
{
scanf("%c",&a[i][j]);
if(a[i][j] == '@')
{
x=i;
y=j;
}
} }
key[x][y]=true;
ans=;
f(x,y);
printf("%d\n",ans+);
}
}
最新文章
- .net5的异步
- SQL sp_executesql【转】
- hdu 2049 不容易系列之(4)——考新郎
- JS框架比较
- 2016年10月15日 星期六 --出埃及记 Exodus 18:26
- Struts2---Result(传统Web应用程序与Ajax应用程序的异同)
- winserver-查看登陆日志
- android自动化必备之SDK
- python常用模块——collections
- Linux系统下的网络配置
- 虚拟机安装ubuntu18.04及其srs服务器的搭建
- Linux内核设计与实现 第四章
- 浅谈JS的变量提升
- [UE4]爆头和穿墙
- Leetcode题库——21.合并两个有序链表
- 调试查看CLR运行代码
- Linux内核剖析 之 内存管理
- jmap查看内存使用情况与生成heapdump--转
- Dropbox的CEO在MIT的毕业演讲
- webDriver API——第11部分Remote WebDriver