站外题,选3关
查看原帖
站外题,选3关
1039211
Wendy_Hello_qwq楼主2024/5/1 20:51

1375.【信息学奥赛课课通】瓷砖

时间限制: 1 s

空间限制: 256 MB

题目描述

在一个 w×h 的矩形广场上,每一块 1×1 的地面都铺设了红色或黑色的瓷砖。小林同学站在某一块黑色的瓷砖上,他可以从此处出发,移动到上、下、左、右四个相邻的且是黑色的瓷砖上。现在,他想知道,通过重复上述移动所能经过的黑色瓷砖数。注意,小林站的位置也算一块黑色瓷砖。

输入

从文件 tile.in 中读入数据。

第 1 行为 h、w,2≤w、h≤50,之间有一个空格隔开。

以下为 1 个 w 行 h 列的二维字符矩阵,每个字符为“.”“#”“@”,分别表示该位置为黑色的瓷砖、红色的瓷砖、小林的初始位置。

输出

输出到文件 tile.out 中。

输出一行一个整数,表示小林从初始位置出发经过的黑色瓷砖数。

样例输入

11 9

.#.........

.#.#######.

.#.#.....#.

.#.#.###.#.

.#.#..@#.#.

.#.#####.#.

.#.......#.

.#########.

...........

样例输出

59

上代码

#include <cstdio>
using namespace std;
char ch, a[57][57];
int h, w, ans = 1, p, q, dx[4] = {-1, 0, 1, 0}, dy[4] = {0, 1, 0, -1};
void dfs (int, int);
int main()
{
	freopen ("tile.in", "r", stdin);
	freopen ("tile.out", "w", stdout);
	scanf ("%d%d", &h, &w);
	for (int i = 1; i <= w; i++)
	{
		getchar ();
		for (int j = 1; j <= h; j++)
		{
			scanf ("%c", &ch);
			a[i][j] = ch;
			if (ch == '@')
			{
				p = i;
				q = j;
			}
		}
	}
	dfs (p, q);
	printf ("%d", ans);
	return 0;
//	fclose (stdin); fclose (stdout);
}
void dfs (int x, int y)
{
	a[x][y] = '#';
	for (int i = 0; i <= 3; i++)
	{
		int xx = x + dx[i];
		int yy = y + dy[i];
		if (xx >= 1 && xx <= w && yy >= 1 && yy <= h && a[xx][yy] == '.')
		{
			ans++;
			dfs (xx, yy);
		}
	}
}

为什么不对啊喂......

2024/5/1 20:51
加载中...