poj 1941 The Sierpinski Fractal(递归)

程序设计实习动态规划作业 poj 1941 The Sierpinski Fractal(递归)
总时间限制: 1000ms 内存限制: 65536kB

描述
Consider a regular triangular area, divide it into four equal triangles of half height and remove the one in the middle. Apply the same operation recursively to each of the three remaining triangles. If we repeated this procedure infinite times, we’d obtain something with an area of zero. The fractal that evolves this way is called the Sierpinski Triangle. Although its topological dimension is 2, its Hausdorff-Besicovitch dimension is log(3)/log(2)~1.58, a fractional value (that’s why it is called a fractal). By the way, the Hausdorff-Besicovitch dimension of the Norwegian coast is approximately 1.52, its topological dimension being 1.

For this problem, you are to outline the Sierpinski Triangle up to a certain recursion depth, using just ASCII characters. Since the drawing resolution is thus fixed, you’ll need to grow the picture appropriately. Draw the smallest triangle (that is not divided any further) with two slashes, to backslashes and two underscores like this:

/\
/_\
To see how to draw larger triangles, take a look at the sample output.

输入
The input contains several testcases. Each is specified by an integer n. Input is terminated by n=0. Otherwise 1<=n<=10 indicates the recursion depth.

输出
For each test case draw an outline of the Sierpinski Triangle with a side’s total length of 2n characters. Align your output to the left, that is, print the bottom leftmost slash into the first column. The output must not contain any trailing blanks. Print an empty line after each test case.

样例输入
3
2
1
0

样例输出
poj 1941 The Sierpinski Fractal(递归)_第1张图片

提示

The Sierpinski-Triangle up to recursion depth 7

来源
Ulm Local 2002

本题容易想到递归画图,但是不设置画布有些麻烦,必须同时考虑每一行的三角形的偏置,好在数据十分小,所以设置画布保存一下。经过调试,容易写出正确算法,这真是有趣的一个题目。

#define MAX_SIZE 10

#include<stdio.h>

char map[(1<<MAX_SIZE)+1][(2<<MAX_SIZE)+1];


void print_map(int n)
{
    for (int i=1;i<=(1<<n);i++)
    {
        for (int j=1;j<=(1<<(n))+i;j++)
            printf("%c",map[i][j]);
        printf("\n"); 
    };
    return;
}

void print(int depth,int i0,int j0)
{
    if (depth==1)
    {
        map[1+i0][2+j0]='/';
        map[1+i0][3+j0]='\\';
        map[2+i0][1+j0]='/';
        map[2+i0][2+j0]='_';
        map[2+i0][3+j0]='_';
        map[2+i0][4+j0]='\\';
    }
    else
    {
        print(depth-1,i0,j0+(1<<(depth-1)));
        print(depth-1,i0+(1<<(depth-1)),j0);
        print(depth-1,i0+(1<<(depth-1)),j0+(1<<depth));
    }
    return;
}

int main()
{
    int n;
    while (scanf("%d",&n)&&n)
    {
        for (int i=1;i<=(1<<n);i++)
            for (int j=1;j<=(1<<(n+1));j++)
                map[i][j]=' ';
        print(n,0,0);
        print_map(n);
        printf("\n");
    }
    return 0;
}

你可能感兴趣的:(poj 1941 The Sierpinski Fractal(递归))