#include <stdio.h> #include <stdlib.h> #define MAXSIZE 20 int main() { int m, magic[MAXSIZE][MAXSIZE] = {0}, i = 0,j, x, y; scanf("%d",&m); magic[i][m/2] = 1; x = 0;y =m/2; for(i = 2;i <= m*m ;i++)//我进行的优化及改进 { if(magic[(x-1+m) % m][(y-1+m) % m] == 0) //先进行判断是否理应填的位置是否被占 { x = (x-1+m) % m;//没被占进行赋值操作 y = (y-1+m) % m; } else//否则直接移动到它元素的下方,(横坐标+1)% m,纵坐标不变 { x = (x+1) % m; } magic[x][y] = i; } for(i = 0; i < m ;i++) { for(j = 0;j < m;j++) printf("%d ",magic[i][j]); printf("\n"); } } /*#include <stdio.h>//书上思路 #include <stdlib.h> #define MAXSIZE 20 int main() { int m, magic[MAXSIZE][MAXSIZE] = {0}, i = 0,j, x, y; scanf("%d",&m); magic[i][m/2] = 1; x = 0;y =m/2; for(i = 2;i <= m*m ;i++) { x = (x-1+m) % m;//先找到理应的位置直接将横纵坐标进行赋值 y = (y-1+m) % m; if(magic[x][y] != 0 )//如果不等于0,此位置被占 { x = (x+2+m) % m;//注意x在之前被改动到理应存在的位置,注意理应存在的位置和上一个元素下面位置的关系 y = (y+1+m) % m; } magic[x][y] = i; } for(i = 0; i < m ;i++) { for(j = 0;j < m;j++) printf("%d ",magic[i][j]); printf("\n"); } }*/
原文地址:https://www.cnblogs.com/cstdio1/p/10884987.html
时间: 2024-10-01 09:29:15