http://poj.org/problem?id=2083
Fractal
Time Limit: 1000MS | Memory Limit: 30000K | |
Total Submissions: 8317 | Accepted: 3957 |
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
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
递归这个神奇的东西, 然而我并没有会, 唉, 感觉就只是懂了皮毛, 稍微加点难度的就不会, 真失败, 以后好好用用
#include<stdio.h>
#include<string.h>
#define N 1100
int a[20];
bool G[N][N];
void DFS(int n, int x, int y)
{
G[x][y] = true;
if(n==7)
return ;
int s = a[n];
DFS(n+1, x, y);
DFS(n+1, x, y+s*2 );
DFS(n+1, x+s, y+s);
DFS(n+1, x+s*2, y);
DFS(n+1, x+s*2, y+s*2);
}
int main()
{
int i, j, n;
memset(G, false, sizeof(G));
a[1] = 1;
for(i=2; i<=10; i++)
a[i] = a[i-1]*3;
DFS(1, 1, 1);
while(scanf("%d", &n), n!=-1)
{
for(i=1; i<=a[n]; i++)
{
for(j=1; j<=a[n]; j++)
{
if(G[i][j]==true)
printf("X");
else
printf(" ");
}
printf("
");
}
printf("-
");
}
return 0;
}
下面粘个错误代码, 自己刚开始写的, 仔细看看是我没有很好的注意分层的问题, 在每一层递归的时候,应该记录一下它有用的信息, 然而我并没有。这题, 错就错在没有很好的注意分层的问题
#include<stdio.h> #include<string.h> int n, G[N][N]; void DFS(int x, int y) { G[x][y] = 1; if(x== 3 && y==3) { G[x][y] = 1; return ; } DFS(x, y+2); DFS(x+1, y+1); DFS(x+2, y); DFS(x+2, y+2); } int main() { int n, a[20]={0,1}; memset(G, 0, sizeof(G)); for(i=2; i<=10; i++) a[i] = a[i-1]*3; DFS(1, 1); while(scanf("%d", &n), n!=-1) { int i, j; for(i=1; i<=a[n]; i++) { for(j=1; j<=a[n]; j++) { if(G[i][j]==1) printf("X"); else printf(" "); } printf(" "); } printf("- "); } return 0; }