您的位置:首页 > 其它

red and black (深度优先搜索算法dfs)

2015-09-28 10:23 232 查看
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.

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).

问题描述

有一个矩形房间,覆盖着瓷砖。每个瓷砖颜色的红色或黑色。一个人站在一个黑色的瓷砖上。他可以移动四个相邻的瓷砖。但他不能移动在红瓦,他只能移动黑色瓷砖。

编写一个程序计算他通过上述描述重复移动达到的黑色瓷砖的数量。

问题说的直接一点就是:计算他最多可以遍历多少个黑色瓷砖(方向是周围的四个方向),有红砖的地方是不通的。

输入

首次输入两个数值W和H(0

@…

.#..#.

11 9

.#………

.#.#######.

.#.#…..#.

.#.#.###.#.

.#.#..@#.#.

.#.#####.#.

.#…….#.

.#########.

………..

11 6

..#..#..#..

..#..#..#..

..#..#..###

..#..#..#@.

..#..#..#..

..#..#..#..

7 7

..#.#..

..#.#..

.

…@…

.

..#.#..

..#.#..

0 0

Sample Output

45

59

6

13

代码如下:

#include "stdafx.h"
#include <iostream>
using namespace std;

#define M 25
int n , m;
char map[M][M];
bool flag[M][M];
int startx,starty;
int num;
int dir[4][2] = {0,1,
0,-1,
1,0,
-1,0};

// 用来初始化数据
int init()
{
num = 1; // 包含他自己
memset(map, ' ', sizeof(map));
for(int i=0; i<n; i++)
{
getchar();
for(int j=0; j<m; j++)
{
scanf("%c", &map[i][j]);
// 判断是不是人的位置,如果是的话,把他的坐标保存下来
if(map[i][j] == '@')
{
startx=i, starty=j;
}
}
}
return 1;
}

// 用来判断数据是否合法
bool judge(int x, int y)
{
if(x<n&&y<n&&x>=0&&y>=0&&map[x][y]=='.')
return true;
return false;
}

// 形参中的x,y是人的初始位置
int dfs(int x, int y)
{
int i,j;
int tx = x, ty = y;
map[tx][ty] = '#';
// 分辨遍历四个方向,来判断是否合乎要求。
for(i=0; i<4; i++)
{
if(judge(tx+dir[i][0], ty+dir[i][1]))
{
num++;
// 如果有一个方向的点满足要求,重新初始位置,进行递归。
dfs(tx+dir[i][0], ty+dir[i][1]);
}
}
return num;
}

int main()
{
while(cin>>m>>n&&m&&n)
{
init();
cout << dfs(startx, starty) << endl;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息