代码
#include <iostream>
using namespace std;
int main() {
int N;
char a[2];
bool isFirst = true;
while(cin>>N>>a[0]>>a[1]) {
if(isFirst) {
isFirst = false;
} else {
cout<<endl;
}
if(N==1) {
cout<<a[0]<<endl;
} else {
char c[N][N];
int count = 3;
int level = 1;
c[N/2][N/2] = a[0];
for(int i=N/2-1; i>=0; i--) {
for(int j=0; j<count; j++) {
c[i][i+j] = a[level%2];
}
for(int j=0; j<count; j++) {
c[i+j][i] = a[level%2];
}
for(int j=0; j<count; j++) {
c[i+count-1][i+j] = a[level%2];
}
for(int j=0; j<count; j++) {
c[i+j][i+count-1] = a[level%2];
}
count += 2;
level++;
}
c[0][0] = ' ';
c[0][N-1] = ' ';
c[N-1][0] = ' ';
c[N-1][N-1] = ' ';
for(int i=0; i<N; i++) {
for(int j=0; j<N; j++) {
cout<<c[i][j];
}
cout<<endl;
}
}
}
return 0;
}
注解
1、坑点1:尤其要注意边界条件:n=1
2、核心代码:四个循环,填四周,分别是矩形的四条边。主要注意下标的起始位置,和循环的数量,以及每次的循环输出的字符是内层还是外层字符。
3、坑点2:四个角分别置为空格,注意:跟其他题的区别是,此题结尾的空格也要输出,而不是像其他题目,结尾没有多余空格。