您的位置:首页 > 其它

初入算法篇 (递归)——poj2083

2018-03-25 19:20 369 查看
Fractal
Time Limit: 1000MS Memory Limit: 30000K
Total Submissions: 10757 Accepted: 4836
DescriptionA fractal is an object or quantity that displays self-similarity, in a somewhat technical sense, on all scales. The object need not exhibit exactly the same structure at all scales, but the same "type" of structures must appear on all scales.
A box fractal is defined as below :
A box fractal of degree 1 is simply
X

A box fractal of degree 2 is
X X
X
X X

If using B(n - 1) to represent the box fractal of degree n - 1, then a box fractal of degree n is defined recursively as following
B(n - 1)        B(n - 1)

B(n - 1)

B(n - 1)        B(n - 1)


Your task is to draw a box fractal of degree n.InputThe input consists of several test cases. Each line of the input contains a positive integer n which is no greater than 7. The last line of input is a negative integer −1 indicating the end of input.OutputFor each test case, output the box fractal using the 'X' notation. Please notice that 'X' is an uppercase letter. Print a line with only a single dash after each test case.Sample Input1
2
3
4
-1Sample OutputX
-
X X
X
X X
-
X X X X
X X
X X X X
X X
X
X X
X X X X
X X
X X X X
-
X X X X X X X X
X X X X
X X X X X X X X
X X X X
X X
X X X X
X X X X X X X X
X X X X
X X X X X X X X
X X X X
X X
X X X X
X X
X
X X
X X X X
X X
X X X X
X X X X X X X X
X X X X
X X X X X X X X
X X X X
X X
X X X X
X X X X X X X X
X X X X
X X X X X X X X
-题意:给出样例,让你打出n=1-7的图形

这题目已经明确暗示了用递归去做,大致思路是不会错的,要注意的是相隔距离m,我们可以发现
n=1  m=0
n=2  m=1
n=3  m=3
n=4 m=9
可得到m=3^(n-2)

第一个点(x,y)与中间的距离为(x+m,y+m) 同行右边的(x,y+2*m)那么我们可以写出五个点的递归表达式
    dfs(n-1,x,y);
    dfs(n-1,x,y+2*m);
    dfs(n-1,x+m,y+m);
    dfs(n-1,x+2*m,y);
    dfs(n-1,x+2*m,y+2*m);

边界条件为n==1,记得初始化,然后应该用%s输出,而不是用%c一个个输出,这样直接TLE#include <iostream>
#include <algorithm>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <string.h>
using namespace std;
char map[1000][1000];
void dfs(int n,int x,int y)
{
int m;
if(n==1)
{
map[x][y]='X';
return ;//边界条件
}
m=pow(3.0,n-2);//左右上下相隔距离
dfs(n-1,x,y);
dfs(n-1,x,y+2*m);
dfs(n-1,x+m,y+m);
dfs(n-1,x+2*m,y);
dfs(n-1,x+2*m,y+2*m);

}
int main()
{
int t;
int n,i,j;
while(~scanf("%d",&n))
{
if(n==-1) break;
int m=pow(3.0,n-1);
for(i=1; i<=m; i++)
{
for(j=1; j<=m; j++)
{
map[i][j]=' ';//初始化
}
map[i][j]='\0';
}
dfs(n,1,1);
for(i=1; i<=m; i++)
{
printf("%s",map[i]+1);
printf("\n");
}
printf("-\n");
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  初入算法篇 递归