2015d1-t1 神奇的幻方
题意
https://www.luogu.com.cn/problem/P2615
想法
- 模拟
- 每填一个数字,就保存一下这个数的坐标。填下个数的时候,刚才保存的坐标就是 (K - 1) 的坐标。跟据此坐标判断 K 应该填到哪个位置。其中,填第一个数的时候需要特判。
代码
#include <bits/stdc++.h>
using namespace std;
int a[40][40];
int step = 1, n , posx,posy;
int main(){
scanf("%d",&n);
while (step <= n * n )
{
if(step == 1) a[posx = 1][posy = n/2 +1] = step++;
else if (posx == 1 && posy != n ) a[posx = n][++posy] = step++;
else if (posx != 1 && posy == n) a[--posx][posy = 1] = step++;
else if (posx == 1 && posy == n) a[++posx][posy] = step++;
else if (posx != 1 && posy != n ){
if (a[posx - 1][posy + 1] == 0)
a[--posx][++posy] = step++;
else
a[++posx][posy] = step++;
}
}
for (int i = 1; i <= n; ++i) {
for (int j = 1; j <= n; ++j)
cout << a[i][j] << " ";
std::cout << std::endl;
}
return 0 ;
}