码迷,mamicode.com
首页 > 其他好文 > 详细

POJ 1979 Red and Black (红与黑)

时间:2016-09-07 22:56:40      阅读:247      评论:0      收藏:0      [点我收藏+]

标签:

POJ 1979 Red and Black 红与黑

Time Limit: 1000MS    Memory Limit: 30000K

 

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)  The end of the input is indicated by a line consisting of two zeros. 

多组测试用例。每组数组开头有两个正整数WHWH分别表示 x- y- 方向上瓷砖的数量。WW均不超过20

 

还有H行数据,每行包含W个字符。每个字符表示各色瓷砖如下。

 

‘.’- 一块黑砖

‘#’- 一块红砖

‘@’- 一个黑砖上的人(一组数据一个人)

输入以一行两个零为结束。

 

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 - 输出样例

6 9
....#.
.....#
......
......
......
......
......
#@...#
.#..#.
11 9
.#.........
.#.#######.
.#.#.....#.
.#.#.###.#.
.#.#..@#.#.
.#.#####.#.
.#.......#.
.#########.
...........
11 6
..#..#..#..
..#..#..#..
..#..#..###
..#..#..#@.
..#..#..#..
..#..#..#..
7 7
..#.#..
..#.#..
###.###
...@...
###.###
..#.#..
..#.#..
0 0
45
59
6
13

 

【题解】

  数据不大,DFS可解。

【代码 C++

 1 #include <cstdio>
 2 #include <cstring>
 3 char data[25][25];
 4 int sum;
 5 void DFS(int y, int x){
 6     if (data[y][x] == #) return;
 7     ++sum; data[y][x] = #;
 8     DFS(y + 1, x); DFS(y - 1, x);
 9     DFS(y, x + 1); DFS(y, x - 1);
10 }
11 int main(){
12     int w, h, i, j, stY, stX;
13     while (~scanf("%d%d ", &w, &h)){
14         if (w + h == 0) break;
15         memset(data, #, sizeof(data));
16         for (i = 1; i <= h; ++i){
17             gets(&data[i][1]);
18             for (j = 1; j <= w; ++j) if (data[i][j] == @) stY = i, stX = j;
19             data[i][j] = #;
20         }
21         sum = 0; DFS(stY, stX);
22         printf("%d\n", sum);
23     }
24     return 0;
25 }

 

POJ 1979 Red and Black (红与黑)

标签:

原文地址:http://www.cnblogs.com/Simon-X/p/5851280.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!