「POJ2083」Fractal 题解 (递归,分形)
题目简介
Description|题目描述
A 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
Your task is to draw a box fractal of degree \(n\).
分形是在某种技术意义上在所有尺度上显示自相似性的对象或数量。 物体不需要在所有尺度上都具有完全相同的结构,但是相同的“类型”结构必须出现在所有尺度上。
箱形分形定义如下:
1级的盒子分形是简单的
X
2级的盒子分形是
X X
X
X X
如果使用\(B(n - 1)\)来表示\(n - 1\)的盒子分形,那么递归地定义n阶的盒子分形如下
你的任务是绘制一个度为\(n\)的盒子分形。
Input|输入
The 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.
输入包含几个测试用例。 输入的每一行包含一个不大于\(7\)的正整数\(n\)。输入的最后一行是负整数\(-1\),表示输入的结束。
Output|输出
For 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.
对于每个测试用例,使用“X”符号输出框分形。 请注意'X'是一个大写字母。 在每个测试用例后打印一行只有一个短划线。
Sample Input|样例输入
1
2
3
4
-1
Sample Output|样例输出
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 X
-
分析
经过分析
\(i\)级分形盒子 | 行数 | 行表示方法 | 列数 | 列的表示方法 |
---|---|---|---|---|
$$1$$ | $$1$$ | \(0\sim 3^0-1\) | $$1$$ | \(0\sim 3^0-1\) |
$$2$$ | $$3$$ | \(0\sim 3^1-1\) | $$3$$ | \(0\sim 3^1-1\) |
$$3$$ | $$9$$ | \(0\sim 3^2-1\) | $$9$$ | \(0\sim 3^2-1\) |
$$4$$ | $$27$$ | \(0\sim 3^3-1\) | $$27$$ | \(0\sim 3^3-1\) |
- 1.定义一个\(E\)数组
int E[10];
E[0]=1;
for(int i=1;i<8;i++)E[i]=E[i-1]*3;
- 2.我们还需要一个\(char\)类型的\(G\)数组记录地图
while(scanf("%d",&n)){
if(n==-1)break;
memset(G,' ',sizeof(G));
}
记得在每行的末尾打一个终止符'\0'
:
for(int i=0;i<E[n-1];i++)
G[i][E[n-1]]='\0';
- 3.递归
B(n,0,0);
inline void B(int n,int x,int y){
if(n==1){
G[x][y]='X';
return ;
}
B(n-1,x,y);//左上
B(n-1,x,y+(E[n-2]<<1));//右上
B(n-1,x+E[n-2],y+E[n-2]);//正中
B(n-1,x+(E[n-2]<<1),y);//左下
B(n-1,x+(E[n-2]<<1),y+(E[n-2]<<1));//右下
}
代码
#include<bits/stdc++.h>
using namespace std;
int E[10];
char G[1010][1010];
inline void B(int n,int x,int y){
if(n==1){
G[x][y]='X';
return ;
}
B(n-1,x,y);
B(n-1,x,y+(E[n-2]<<1));
B(n-1,x+E[n-2],y+E[n-2]);
B(n-1,x+(E[n-2]<<1),y);
B(n-1,x+(E[n-2]<<1),y+(E[n-2]<<1));
}
int main(){
int n;
E[0]=1;
for(int i=1;i<8;i++)E[i]=E[i-1]*3;
while(scanf("%d",&n)){
if(n==-1)break;
memset(G,' ',sizeof(G));
for(int i=0;i<E[n-1];i++)
G[i][E[n-1]]='\0';
B(n,0,0);
for(int i=0;i<E[n-1];i++)
puts(G[i]);
puts("-");
}
return 0;
}