Fractal解题笔记

题面

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
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.

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.

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.
Sample

1
2
3
4
-1
X
-
X X
 X
X X
-
X X   X X
 X     X
X X   X X
   X X
    X
   X X
X X   X X
 X     X
X X   X X
-
X X   X X         X X   X X
 X     X           X     X
X X   X X         X X   X X
   X X               X X
    X                 X
   X X               X X
X X   X X         X X   X X
 X     X           X     X
X X   X X         X X   X X
         X X   X X
          X     X
         X X   X X
            X X
             X
            X X
         X X   X X
          X     X
         X X   X X
X X   X X         X X   X X
 X     X           X     X
X X   X X         X X   X X
   X X               X X
    X                 X
   X X               X X
X X   X X         X X   X X
 X     X           X     X
X X   X X         X X   X X
-

思路

这道题显然是个递归问题,需要我们找到递归方程,不难发现分形X的相对位置是确定的,我们可以由此推出每一层位置的递归关系;当然另一个角度看,也可以看作图像的平移。为了数组处理方便,我们使用左上角为基点就可以得到一组递归方程,如果不用左上角为基点,就要涉及原点坐标的平移变换,相对麻烦些。

AC代码

#include
#include
#include
#include
using namespace std;

int n, W, cnt;
char s[1001][1001];

void b(int d, int x, int y){
    if(d==1)s[y][x]='X';
    else {
        int size = 1;
        for(int i=2;i<d;i++)size*=3;
        b(d-1,x,y);//左上
        b(d-1,x+2*size,y);//右上
        b(d-1,x+size,y+size);//中
        b(d-1,x,y+2*size);//左下
        b(d-1,x+2*size,y+2*size);//右下
    }
}

int main(){
    int size;
    scanf("%d", &n);
    do{
        memset(s,' ',sizeof(s));//提前填充空格
        b(n,0,0);
        size=1;
        for(int i=1;i<n;i++)size*=3;
        for(int i=0;i<size;i++){
            for(int j=size;j>0;j--)
                if(s[i][j-1]=='X'){
                    s[i][j]='\0';
                    break;
                }
            printf("%s\n",s[i]);        
        }
        printf("-\n");
        scanf("%d", &n);
    }while(n != -1);
}

你可能感兴趣的:(算法,c++,回归)