题目:
样例:
代码:
#include<stdio.h>
struct pos{
int row;
int col;
};
struct pos find(int n, int x, int arr[40][40]){//查找第k-1个数的位置
struct pos po;
for(int i = 0; i < n; i++){
for(int j = 0; j < n; j++){
if(arr[i][j] == x){
po.row = i;
po.col = j;
return po;
}
}
}
}
int main() {
int n, k;
scanf("%d",&n);
k = n * n;
int arr[40][40] = {0};
arr[0][n/2] = 1;//把1放在第一行中间
for(int i = 2; i <= k; i++){
struct pos po = find(n, i - 1, arr);
//r, c = find(n, i - 1, arr);
//printf("%d %d", po.row, po.col);//想看看返回的行列值
if(po.row == 0 && po.col != n - 1){
arr[n - 1][po.col + 1] = i;
}
if(po.row != 0 && po.col == n - 1){
arr[po.row - 1][0] = i;
}
if(po.row == 0 && po.col == n - 1){
arr[po.row + 1][po.col] = i;
}
if(po.row != 0 && po.col != n - 1){
if(arr[po.row - 1][po.col + 1] == 0){
arr[po.row - 1][po.col + 1] = i;
}
else{
arr[po.row + 1][po.col] = i;
}
}
}
for(int i = 0; i < n; i++){
for(int j = 0; j < n; j++){
printf("%d ",arr[i][j]);
}
printf("\n");
}
return 0;
}
输出: