POJ2083 Fractal [Fractal Backtracking]

The scale of the n-degree box fractal is 3 (n-1), that is, the n-degree box fractal graph is a square whose length and width are 3 (n-1).
Set the recursive function printBox(n,x,y) to generate an n-degree box fractal with coordinates (x,y) as the upper left corner.
1) Recursion boundary: If n=1, then output 'X' at (x, y)
2) If n>1, then calculate the size of the n-1 degree box m = 3^(n-2), respectively in Draw 5 boxes of degree n-1 in the upper left, upper right, middle, lower left and lower right.
For the n-1 degree box at the upper left, the coordinates of the upper left corner are (x, y), which is generated by recursive printBox(n-1, x, y); for the n-1 degree box at the upper right, the coordinates of the upper left
corner For (x+2m, y), recursive printBox(n-1, x+2m, y) is generated;
for the middle n-1 degree box, the coordinates of the upper left corner are (x+m, y+m), recursive printBox(n-1,x+m,y+m) is generated;
for the box with n-1 degrees in the lower left, the coordinates of the upper left corner are (x,y+2m), recursive printBox(n-1,x,y +2m) to generate;
for the box with n-1 degrees on the upper right, the coordinates of the upper left corner are (x+2m, y+2m), and recursive printBox(n-1, x+2m, y+2m) is generated

#include<cstdio>
#include<cstring>
#include<algorithm>
#include<math.h>
using namespace std;

char a[735][735];

void dfs(int cur,int x,int y)
{
    if(cur==1)
    {
        a[x][y]='X';
        return ;
    }
    int s=pow(3,cur-2);
    dfs(cur-1,x,y);
    dfs(cur-1,x,y+2*s);
    dfs(cur-1,x+s,y+s);
    dfs(cur-1,x+2*s,y);
    dfs(cur-1,x+2*s,y+2*s);
}

int main()
{
    int n;
    while(~scanf("%d",&n))
    {
        if(n==-1)
            break;
        memset(a,' ',sizeof(a));
        dfs(n,1,1);
        int s=pow(3,n-1);
        for(int i=1;i<=s;i++)
        {
            a[i][s+1]='\0';
        }
        for(int i=1;i<=s;i++)
        {
            printf("%s\n",a[i]+1);
        }
        printf("-\n");
    }
    return 0;
}

Guess you like

Origin blog.csdn.net/Li_Hongcheng/article/details/86563732