打印如下形式的矩阵;
n=5:
1 2 9 10 25
4 3 8 11 24
5 6 7 12 23
16 15 14 13 22
17 18 19 20 21
n=6:
1 2 9 10 25 26
4 3 8 11 24 27
5 6 7 12 23 28
16 15 14 13 22 29
17 18 19 20 21 30
36 35 34 33 32 31
代码:
#include <iostream>
#include <iomanip>
using namespace std;
#define MAX 20
int a[MAX][MAX];
int N;
void display()
{
for (int i=0;i<N;i++)
{
for (int j=0;j<N;j++)
{
cout<<setw(6)<<a[i][j];
}
cout<<endl;
}
cout<<endl;
}
void main()
{
memset(a,0,sizeof(a));
cout<<"input the N "<<endl;
cin>>N;
int tot = 1;
int x=0;
int y=0;
//a[x][y] = tot++;
while (tot<N*N)
{
a[x][y++] = tot++;
//cout<<"右移1"<<x<<" "<<y<<endl;
for(;x<y;x++) a[x][y] = tot++;
//cout<<"down"<<x<<" "<<y<<endl;
for (;y>0;y--) a[x][y] = tot++;
//cout<<"left"<<x<<" "<<y<<endl;
a[x++][y] = tot++;
//cout<<"下移1"<<x<<" "<<y<<endl;
for (;y<x;y++) a[x][y] = tot++;
//cout<<"右移"<<x<<" "<<y<<endl;
for (;x>0;x--) a[x][y] = tot++;
//cout<<"up"<<x<<" "<<y<<endl;
}
if (N%2)
{
a[0][N-1] = N*N;
}
display();
}