杭电 1312 Red and Black 递归 附翻译

Red and Black

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

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
 

 

问题描述

这里有一间铺满方砖(square tiles)的长方形(rectangular)屋子。每一片瓷砖不是红色就是黑色。一个人站在一块黑色的瓷砖上,从这里,他能移动到四个邻近的(adjacent)瓷砖之一,但是他不能走红色瓷砖,他只能走黑的。

写出一个程序能够计算能够按照上述条件重复移动的黑瓷砖数量。

 

输入

重复输入多(multiple多样的)组(sets套)数据。每组数据的第一行包含两个正整数W和H,W和H各自(respectively)代表x,y方向上的瓷砖数,两数均不超过20,现在又H行的数据,每行包含W个字符,如下所示,每个字符代表着一种颜色的砖:

' . '黑砖

'#'红砖

'@'初位置

 

输出

对每一组数据,你的程序应输出一行包含他能到达的所有黑砖的总(intial)数(包括初位置)。

 

感觉递归就像俄罗斯套娃一样,一层套一层。。怎么说,对于学长给的代码可以理解,不过嘛,总觉得理解的不是太透彻。。或许我需要时间来接受它。

注意:在搜索的时候,x对应的是m(纵坐标),y对应的是n(横坐标),至于为什么这样,具体操作一下就知道了。另外要标记一下已用过的点。

return ;表示退出当前的操作。

 

#include

char a[22][22];
int count,n,m;

void fab(int x,int y){
	if(a[x][y]=='#') 
	return ;
	if(x<1||x>m||y<1||y>n)
	return ;
	count++;
	a[x][y]='#';
	fab(x+1,y);
	fab(x-1,y);
	fab(x,y+1);
	fab(x,y-1);
}

int main(){
	int x,y,i,j;
	while(scanf("%d%d",&n,&m),n|m){
		count=0;
		for(i=1;i<=m;i++){
			getchar();
			for(j=1;j<=n;j++){
				scanf("%c",&a[i][j]);
				if(a[i][j]=='@')
				x=i,y=j;
			}
		}
		fab(x,y);
		printf("%d\n",count);
	}
	return 0;
}

你可能感兴趣的:(递归,c语言,HDOJ)