代码如下:
#include <stdio.h>
int main()
{
const int n = 5;
int a[n][n] = { 0 };
int i = 0;
int j = n / 2;
int row, col;
for (int k = 1; k <= n*n; ++k)
{
a[i][j] = k;
row = i-1;
col = j + 1;
if (row < 0) row += n;
if (col >= n) col -= n;
if (a[row][col] != 0)
{
row = i + 1;
col = j;
}
i = row;
j = col;
}
for (int i = 0; i < n; ++i)
{
for (int j = 0; j < n; ++j)
{
printf("%-3d", a[i][j]);
}
puts("");
}
return 0;
}
运行结果