版权声明:反正也没有人会转,下一个 https://blog.csdn.net/drtlstf/article/details/83150326
Description
在一个 w×h 的矩形广场上,每一块 1×1 的地面都铺设了红色或黑色的瓷砖。小林同学站在某一块黑色的瓷砖上,他可以从此处出发,移动到上、下、左、右四个相邻的且是黑色的瓷砖上。现在,他想知道,通过重复上述移动所能经过的黑色瓷砖数。
Input
第 1 行为 h、w,2≤w、h≤50,之间由一个空格隔开;
以下为一个 w 行 h 列的二维字符矩阵,每个字符为“.”“#”“@”,分别表示该位置为黑色的瓷砖、红色的瓷砖、小林的初始位置。
Output
输出一行一个整数,表示小林从初始位置出发经过的黑色瓷砖数。
Sample Input
11 9
.#.........
.#.#######.
.#.#.....#.
.#.#.###.#.
.#.#..@#.#.
.#.#####.#.
.#.......#.
.#########.
...........
Sample Output
59
当年的DFS模板题.
#include <iostream>
#define SIZE 110
using namespace std;
int res;
bool a[SIZE][SIZE];
int dx[4] = {1, -1, 0, 0};
int dy[4] = {0, 0, 1, -1};
void dfs(int x, int y) // 深度优先搜索
{
int i;
if (!a[x][y]) // 如果不能走就直接返回
{
return;
}
a[x][y] = false;
++res; // 计数器
for (i = 0; i < 4; ++i)
{
dfs(x + dx[i], y + dy[i]); // 四向搜索
}
return;
}
int main(void)
{
int n, m, i, j, sx, sy;
char c;
scanf("%d%d", &m, &n);
for (i = 1; i <= n; ++i)
{
for (j = 1; j <= m; ++j)
{
cin >> c;
if (c == '.')
{
a[i][j] = true;
}
else if (c == '@')
{
a[i][j] = true; // 起点
sx = i;
sy = j;
}
}
}
dfs(sx, sy);
printf("%d", res);
return 0;
}