1C: 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)

The end of the input is indicated by a line consisting of two zeros.

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

题意

有一个长方形的房间,覆盖着正方形的瓷砖。每个磁贴都被着色为红色或黑色。一个人站在黑色的瓷砖上。他可以从一个图块移动到四个相邻图块之一。但是他不能在红色瓷砖上移动,只能在黑色瓷砖上移动。

编写一个程序,通过重复上述动作来计算他可以到达的黑色瓷砖的数量。
输入项
输入包含多个数据集。数据集从包含两个正整数W和H的行开始; W和H分别是x和y方向上的图块数。 W和H不超过20。

数据集中还有H行,每行包含W个字符。每个字符表示瓦片的颜色,如下所示。

‘。’ -黑色瓷砖
‘#’-红色方块
‘@’-黑色瓷砖上的一个人(在数据集中只出现一次)
输入的结尾由包含两个零的线表示。
输出量
对于每个数据集,您的程序应输出一行,其中包含他可以从初始磁贴(包括其自身)达到的磁贴数量。

解法

又是一道dfs水题,找到@,开始暴搜, 遇到‘#’就回溯

代码

#include <iostream>
#include <cstring>
using namespace std;

int dir[4][2] = {1,0, 0,1, -1,0, 0,-1};
bool vis[25][25];
char map[30][30];
int ans = 1;
int n, m;

void dfs(int x, int y) {
	int tx, ty;
	for(int i=0; i<4; ++i) {
		tx = x + dir[i][0];
		ty = y + dir[i][1];
		if(!vis[tx][ty] && map[tx][ty]=='.' && tx>0 && ty>0 && tx<=m && ty<=n) {
			ans++;
			vis[tx][ty] = 1;
			dfs(tx, ty);
		}
	}
	return ;
}

int main() {
	cin >> n >> m;
	while(n!=0 && m!=0) {
		memset(map, 0, sizeof(map));
		for(int i=1; i<=m; ++i) {
			for(int j=1; j<=n; ++j) {
				cin >> map[i][j];
			}
		}
		
		for(int i=1; i<=m; ++i) {
			for(int j=1; j<=n; ++j) {
				if(map[i][j]=='@') {
					vis[i][j] = 1;
					dfs(i, j);
					goto A;
				}
			}
		}
		A:
		cout << ans << endl;
		ans = 1;
		cin >> n >> m;
		memset(vis, 0, sizeof(vis));
	}

	return 0;
}
发布了14 篇原创文章 · 获赞 0 · 访问量 154

猜你喜欢

转载自blog.csdn.net/loaf_/article/details/103959582