atcoder ABC 357-C题详解
Problem Statement
For a non-negative integer K, we define a level-Kcarpet as follows:
A level-0 carpet is a 1×1 grid consisting of a single black cell.
For K>0, a level-K carpet is a 3K×3Kgrid. When this grid is divided into nine 3K−1×3K−1 blocks:
The central block consists entirely of white cells.
The other eight blocks are level-(K−1) carpets.
You are given a non-negative integer N.
Print a level-N carpet according to the specified format.
Constraints
0≤N≤6
N is an integer.
Input
The input is given from Standard Input in the following format:
Output
Print 3N lines.
The i-th line (1≤i≤3N) should contain a string Si of length 3N consisting of . and #.
The j-th character of Si (1≤j≤3N) should be # if the cell at the i-th row from the top and j-th column from the left of a level-N carpet is black, and . if it is white.
Sample Input 1
1
Sample Output 1
#.#
A level-1 carpet is a 3×3 grid as follows:
When output according to the specified format, it looks like the sample output.
Sample Input 2
2
Sample Output 2
#########
#.##.##.#
#########
###…###
#.#…#.#
###…###
#########
#.##.##.#
#########
A level-2 carpet is a 9×9 grid.
思路分析:
本题可以用递归来实现,其中要把八个小正方形全部遍历到,需要用八个坐标。把白色的地毯赋值为1。
code:
#include <iostream>
#include <cmath>
using namespace std;
int a[2000][2000];//0:黑,1:白
void dfs(int x,int y,int k){
if(k==0){
a[x][y]=0;
return ;
}
dfs(x,y,k-1);
dfs(x+pow(3,k-1),y,k-1);
dfs(x+pow(3,k-1)*2,y,k-1);
dfs(x,y+pow(3,k-1),k-1);
dfs(x,y+pow(3,k-1)*2,k-1);
dfs(x+pow(3,k-1),y+pow(3,k-1)*2,k-1);
dfs(x+pow(3,k-1)*2,y+pow(3,k-1),k-1);
dfs(x+pow(3,k-1)*2,y+pow(3,k-1)*2,k-1);
for(int i=x+pow(3,k-1);i<x+pow(3,k-1)*2;i++){
for(int j=y+pow(3,k-1);j<y+pow(3,k-1)*2;j++){
a[i][j]=1;
}
}
}
int main(){
int n;
cin>>n;
dfs(0,0,n);
for(int i=0;i<pow(3,n);i++){
for(int j=0;j<pow(3,n);j++){
if(a[i][j]) cout<<'.';
else cout<<'#';
}
cout<<endl;
}
}