输出方阵

输入一个整数,输出n*n矩阵

输出数字范围为1到n*n,

可以看做一个一个正方形边框放置而成,边框长度为n

每一个正方形框的长度为

n为偶数时 4+4*(n-2)

n为奇数时 1+4*(n-2)

代码如下:

#include<iostream>
using namespace std;
int main()
{
    int n;
    while(cin>>n){
    int a[n+1][n+1];
    int x,y;
    int num=1;
    for(int i=n;i>0;i=i-2){
        int t=(n-i)/2;
//        cout<<"t="<<t<<endl;
        x=y=t+1;
        if(i==1){
            a[x][x]=num++;
            break;
        }
//cout<<"i="<<i<<endl;
        for(;y<=(n-t);y++) a[x][y]=num++;
        y--;
//        cout<<"y="<<y<<endl;
        x++; 
//        cout<<"x="<<x<<endl;
        for(;x<=(n-t);x++) a[x][y]=num++;
        x--;
        y--;
//        cout<<"y "<<y<<endl;
        for(;y>=(t+1);y--) a[x][y]=num++;
        y++;
        x--;
//        cout<<"x"<<x<<endl;
        for(;x>(t+1);x--) a[x][y]=num++;
        
    }
    
    for(int i=1;i<=n;i++){
        for(int j=1;j<=n;j++)
        cout<<a[i][j]<<" ";
        cout<<endl;
    }
} 
}
View Code

猜你喜欢

转载自www.cnblogs.com/helloworld2019/p/10371730.html