A31017.方阵填数
2025-08-05 14:17:04
发布于:浙江
8阅读
0回复
0点赞
#include <iostream>
#include <cstring>
using namespace std;
int main(){
int n;
cin>>n;
int a[n][n];
memset(a,0,sizeof(a));
int d=1;
int y=0;
int x=n-1;
int v=1;
int nn=n*n;
while(v<=nn){
a[y][x]=v;
bool zw;
if(d==1){
zw=false;
if(y==n-1)
zw=true;
else if(a[y+1][x]>0)
zw=true;
if(zw){
d=2;
x--;
}
else{
y++;
}
}
else if(d==2){
zw=false;
if(x==0)
zw=true;
else if(a[y][x-1]>0)
zw=true;
if(zw){
d=3;
y--;
}
else{
x--;
}
}
else if(d==3){
zw=false;
if(y==0)
zw=true;
else if(a[y-1][x]>0)
zw=true;
if(zw){
d=4;
x++;
}
else{
y--;
}
}
else{
zw=false;
if(x==n-1)
zw=true;
else if(a[y][x+1]>0)
zw=true;
if(zw){
d=1;
y++;
}
else{
x++;
}
}
v++;
}
for(int y=0;y<n;y++){
for(int x=0;x<n;x++){
if(x>0)
cout<<" ";
cout<<a[y][x];
}
cout<<endl;
}
return 0;
}
这里空空如也
有帮助,赞一个