例如:
1 2 3
8 9 4
7 6 5
#include<iostream>
#include<stdlib.h>
using namespace std;
void print(int **a, int x, int y, int num, int n)
{
if(n <= 0)
{
return;
}
if(n == 1)
{
a[x][y] = num;
return;
}
for(int i = x; i < n + x - 1 ; i++)
{
a[y][i] = num++;
}
for(int i = y ; i < y + n - 1; i++)
{
a[i][y + n - 1] = num++;
}
for(int i = x + n - 1; i > x; i--)
{
a[y + n - 1][i] = num++;
}
for(int i = y + n - 1; i > y; i--)
{
a[i][x] = num++;
}
//cout << num;
print(a, x + 1, y + 1, num, n - 2);
}
int main()
{
int **a;
a = (int **)malloc(5 * sizeof(int *));
for(int i = 0; i < 5; i++)
a[i] = (int *)malloc(5 * sizeof(int *));
int n;
cin >> n;
print(a, 0, 0, 1, n);
for(int i = 0; i < n; i++)
{
for(int j = 0; j < n; j++)
cout << a[i][j] << " ";
cout << endl;
}
}