花了一个小时,写出。
#include<iostream>
using namespace std;
int a[1005][1005];
int main(){
int n;
cin>>n;
int i=-1,j=0,t=0;//设值
int p=0;//控制循环
for(int k=0;k<2n-1;k++){
if(k<n){
if(k%2==1){
t++,j++,p++;
for(int l=0;l<p;l++){
a[i][j]=t;
if(l!=p-1)i++,j--,t++;
}
}else{
i++,t++,p++;
for(int l=0;l<p;l++){
a[i][j]=t;
if(l!=p-1)i--,j++,t++;
}
}
}else{
if(k%2==1){
a[i][j]=t;
j++,p--;
for(int l=0;l<p;l++){
a[i][j]=t;
i++,j--,t++;
}
}else{
a[i][j]=t;
i++,p--;
for(int l=0;l<p;l++){
a[i][j]=t;
i--,j++,t++;
}
}
}
}
a[n-1][n-1]=n
n;
for(int ii=0;ii<n;ii++){
for(int jj=0;jj<n;jj++){
cout<<a[ii][jj];
if(jj!=n-1) cout<<" ";
}
if(ii!=n-1)cout<<endl;
}
return 0;
}
通过修改
#include<iostream>
using namespace std;
int a[1005][1005];
int main(){
int n;
cin>>n;
int i=-1,j=0,t=0;//设值
int p=0;//控制循环
for(int k=0;k<2n-1;k++){
if(k<n){
if(k%2==1){
t++,j++,p++;
for(int l=0;l<p;l++){
a[i][j]=t;
if(l!=p-1)i++,j--,t++;
}
}else{
i++,t++,p++;
for(int l=0;l<p;l++){
a[i][j]=t;
if(l!=p-1)i--,j++,t++;
}
}
}else{
if(k%2==1){
i++,p--,t++;
for(int l=0;l<p;l++){
a[i][j]=t;
if(l!=p-1)i++,j--,t++;
}
}else{
j++,p--,t++;
for(int l=0;l<p;l++){
a[i][j]=t;
if(l!=p-1)i--,j++,t++;
}
}
}
}
a[n-1][n-1]=n
n;
for(int ii=0;ii<n;ii++){
for(int jj=0;jj<n;jj++){
cout<<a[ii][jj];
if(jj!=n-1) cout<<" ";
}
if(ii!=n-1)cout<<endl;
}
return 0;
}
两个部分比较变换的大小不同,角度也不同。
最后简单方法,把不必要的也计算到了里面
#include<bits/stdc++.h>
using namespace std;
int main()
{
int n,i,j,sum=0;
scanf("%d",&n);
int a[1000][1000];
for(i=0;i<2*n-1;i++)
{
for(j=i;j>=0;j--)
{
if(j<n&&i-j<n)
sum++;
if(i%2!=0)
a[i-j][j]=sum;
else
a[j][i-j]=sum;
}
}
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
printf("%d ",a[i][j]);
printf("\n");
}
return 0;
}</iostream></iostream>