【基础】回形方阵c++
·
描述
输入n打印回形方阵。
输入描述
一个整数n (0 < n < 10)
输出描述
一个方阵,每个数字的场宽为2
用例输入 1
8
用例输出 1
8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 8 8 7 6 6 6 6 6 6 6 6 6 6 6 6 6 7 8 8 7 6 5 5 5 5 5 5 5 5 5 5 5 6 7 8 8 7 6 5 4 4 4 4 4 4 4 4 4 5 6 7 8 8 7 6 5 4 3 3 3 3 3 3 3 4 5 6 7 8 8 7 6 5 4 3 2 2 2 2 2 3 4 5 6 7 8 8 7 6 5 4 3 2 1 1 1 2 3 4 5 6 7 8 8 7 6 5 4 3 2 1 0 1 2 3 4 5 6 7 8 8 7 6 5 4 3 2 1 1 1 2 3 4 5 6 7 8 8 7 6 5 4 3 2 2 2 2 2 3 4 5 6 7 8 8 7 6 5 4 3 3 3 3 3 3 3 4 5 6 7 8 8 7 6 5 4 4 4 4 4 4 4 4 4 5 6 7 8 8 7 6 5 5 5 5 5 5 5 5 5 5 5 6 7 8 8 7 6 6 6 6 6 6 6 6 6 6 6 6 6 7 8 8 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8
来源
二维数组
代码
#include<bits/stdc++.h>
using namespace std;
int a[105][105]={},i,j,n;
int sh(int s,int d,int x,int y){
if(d==4){
d=d%4;
s--;
}
a[x][y]=s;
if(s==0){
return 0;
}
else{
if(d==0){
if(y+1<=2*n+1&&a[x][y+1]==0){
sh(s,d,x,y+1);
}
else{
sh(s,d+1,x+1,y);
}
}
else{
if(d==1){
if(x+1<=2*n+1&&a[x+1][y]==0){
sh(s,d,x+1,y);
}
else{
sh(s,d+1,x,y-1);
}
}
else{
if(d==2){
if(y-1>=1&&a[x][y-1]==0){
sh(s,d,x,y-1);
}
else{
sh(s,d+1,x-1,y);
}
}
else{
if(x-1>=1&&a[x-1][y]==0){
sh(s,d,x-1,y);
}
else{
sh(s,d+1,x,y+1);
}
}
}
}
}
}
int main(){
cin>>n;
sh(n,0,1,1);
for(i=1;i<=2*n+1;i++){
for(j=1;j<=2*n+1;j++){
cout<<setw(2)<<a[i][j];
}
cout<<"\n";
}
return 0;
}
更多推荐
所有评论(0)