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 :
Your task is to draw a box fractal of degree n.
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 Input
1
2
3
-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
-
思路:采用分治思想,将同一类型的问题分解成规模更小的问题,用深搜解决
代码如下:
#include <cstdio>
#define Max 729 + 5
char matrix[Max][Max];
void DFS(int n,int x,int y)
{
if (n == 1)
{
matrix[x][y] = 'X';
return;
}
else
{
int size = 1;
for (int i = 2; i < n; i++)
size *= 3;
DFS(n - 1,x,y);//左上角
DFS(n - 1,x,y + 2 * size);//右上角
DFS(n - 1,x + size,y + size);//中间
DFS(n - 1,x + 2 * size,y);//左下角
DFS(n - 1,x + 2 * size,y + 2 * size);//右下角
}
}
int main()
{
int n;
while (scanf("%d",&n) == 1 && (n + 1))
{
int size = 1;
for (int i = 1; i < n; i++)
size *= 3;
for (int j = 0; j < size; j++)//初始化
{
for (int k = 0; k < size; k++)
matrix[j][k] = ' ';
matrix[j][size] = '\0';
}
DFS(n,0,0);
for (int k = 0; k < size; k++)
printf("%s\n",matrix[k]);
printf("-\n");
}
return 0;
}