首页 > 其他 > 详细

1504061021-hd-Red and Black

时间:2015-04-06 11:27:02      阅读:238      评论:0      收藏:0      [点我收藏+]

Red and Black

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 11542    Accepted Submission(s): 7185


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
 解题思路
        这是一道最基础的深搜,也是朋友教给我的,以前都是不懂。
         深搜就是从一个点向上下左右四个方向拓展,然后再以拓展的点为基础向上下左右拓展判断。
         所以需要两个数组,bianx[4]和biany[4]来存储x和y的对应变化,一定要注意x、y的变话要对照。
        然后还需要判断地点有意义,即在范围之内1<=x<=n&&1<=y<=m
解题代码
#include<cstdio>
#include<cstring>
#include<iostream>//
using namespace std;//C++要加这两个头文件 
char map[22][22];
int bx[5]={0,1,0,-1};
int by[5]={1,0,-1,0};
int sum;
int n,m;
bool judge(int a,int b)
{
	if(a<1||a>m||b<1||b>n)
	    return false;
	else
	{
		if(map[a][b]!='#')
		    return true;
		else
		    return false;
	}
}
void dfs(int a,int b)
{
	int i;
	int nowa,nowb;
	sum++;
	map[a][b]='#';
	for(i=0;i<4;i++)
	{//对定点进行上下左右四种变化 
		nowa=a+bx[i];
		nowb=b+by[i];
		if(judge(nowa,nowb))
		    dfs(nowa,nowb);
		//直接递归调用就好 
		else
		    continue;
	}
}
int main()
{
	//int n,m;
	int i,j,k;
	int stax,stay;
	while(scanf("%d%d",&n,&m),n+m)
	{
		memset(map,0,sizeof(map));
		for(i=1;i<=m;i++)
		    for(j=1;j<=n;j++)
		    {
		    	cin>>map[i][j];
		    	if(map[i][j]=='@')
		    	{
		    		stax=i;
		    		stay=j;
		    	}
		    }
		sum=0;
		dfs(stax,stay);
		cout<<sum<<endl;
		//若输出需要换行,则加上<<endl 
	}
	return 0;
}


1504061021-hd-Red and Black

原文:http://blog.csdn.net/wangluoershixiong/article/details/44900357

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!