HDU1312——Red and Black(DFS)

时间:2023-03-08 22:34:44

Red and Black

Problem 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

题目大意:

    一个瓦片地图,'.'代表黑色的瓦片,'#'代表红色的瓦片,'#'是主人公站的位置,主人公只会下上左右四种移动方式,且只能去黑色的瓦片(初始位置也是黑色的瓦片);

    求可以去的黑色瓦片个数,包括初始位置。

解题思路:

    简单的DFS,搜索一下与初始位置上下左右相连的所有黑色瓦片,并记录输出即可。

Code;

 #include<iostream>
#include<string>
#include<cstdio>
#define MAXN 50
using namespace std;
bool vis[MAXN+][MAXN+],is_black[MAXN+][MAXN+]; //黑色瓦片标记
char tile[MAXN+][MAXN+];
int n,m;
int dfs(int i,int j)
{ if (is_black[i][j]==||vis[i][j]==) return ; //搜索时遇到已经搜索过的或者红色瓦片则返回,不记录瓦片数。
vis[i][j]=;
int sum=;
if (i->=) sum+=dfs(i-,j); //搜索上下左右四种情况
if (i+<=n) sum+=dfs(i+,j);
if (j->=) sum+=dfs(i,j-);
if (j+<=m) sum+=dfs(i,j+);
return sum;
}
int main()
{
int first_i,first_j;
while (cin>>m>>n)
{
if (m==&&n==) break;
memset(is_black,,sizeof(is_black));
memset(vis,,sizeof(vis));
getchar();
for (int i=; i<=n; i++)
{
for (int j=; j<=m; j++)
{
cin>>tile[i][j];
if (tile[i][j]=='@') first_i=i,first_j=j,tile[i][j]='.'; //记录初始位置用于调用DFS,并用题意将初始位置转换成黑色瓦片(貌似没有必要--!)
if (tile[i][j]=='#') is_black[i][j]=;//用Is_Black数组标记瓦片颜色
else is_black[i][j]=;
}
getchar();
} printf("%d\n",dfs(first_i,first_j));
}
return ;
}