有些题目用递归做能明显缩短代码;十分方便,但同样不好理解;
下面是有关递归的题目和代码,希望可以通过题目的训练和对代码的理解能帮助你对递归的理解;
递归运用一
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
#include<stdio.h>
#include<string.h>
int a,b,n,m;
char c[22][22];
int app(int a,int b)
{
if(c[a][b]=='#'||a>=m||b>=n||a<0||b<0)
return 0;
else
{
c[a][b]='#';
return 1+app(a,b+1)+app(a,b-1)+app(a-1,b)+app(a+1,b);//实现了四个方向的搜索,并且每次搜索的可走性实现数量的加1;
}
}
int main()
{
int i,j;
while(scanf("%d%d",&n,&m),n||m)
{
for(i=0; i<m; i++)
{
getchar();
for(j=0; j<n; j++)
{
scanf("%c",&c[i][j]);
if(c[i][j]=='@')
{
a=i;
b=j;
}
}
}
n=app(a,b);
printf("%d\n",n);
}
return 0;
}
递归运用二
蒜头君有一个集合 MM 是这样生成的:
(1) 已知 kk 是集合 MM 的元素;
(2) 如果 yy 是 MM 的元素,那么,2y+12y+1 和 3y+13y+1 都是 MM 的元素;
(3) 除了上述二种情况外,没有别的数能够成为 MM 的一个元素。
问题:给定 kk 和 xx(0 \le k \le x \le 10^50≤k≤x≤10
5
),请判断 xx 是否是 MM 的元素。
如果是,则输出"YES",否则,输出"NO"。
输入格式
输入整数 kk 和 xx,逗号间隔。
输出格式
如果是,则输出"YES",否则,输出"NO"。
输出时每行末尾的多余空格,不影响答案正确性
样例输入
0,22
样例输出
YES
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
using namespace std;
int k,x;
int app(int k)
{
if(k>x) return 0;
if(k==x) return 1;
if(app(2*k+1)||app(3*k+1)) return 1;//实现了两者的混合计算
接下来两行结果也对
// if(app(2*k+1)) return 1;
//if(app(3*k+1)) return 1;
接下来一行不对
// app(2*k+1),app(3*k+1);
}
int main()
{
int t;
cin>>k;
cin.get();
cin>>x;
t=app(k);
if(t)
cout<<"YES"<<endl;
if(!t)
cout<<"NO"<<endl;
return 0;
}