洛谷 P2615 神奇的幻方

题目链接

https://www.luogu.org/problemnew/show/P2615

题解

其实很简单嘛,模拟就好啦。。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
#include <iostream>
#include <algorithm>

using namespace std;

int a[45][45] = { 0 };

int main()
{
int n;
int k, prevX, prevY;

cin >> n;

a[1][n/2+1] = 1; // 首先将 1 放在第一行中间
k = 1;
prevX = 1, prevY = n/2+1;

k++;

while (k <= n*n)
{
if (prevX == 1 && prevY != n)
{
a[prevX = n][++prevY] = k++;
} else if (prevY == n && prevX != 1) {
a[--prevX][prevY = 1] = k++;
} else if (prevX == 1 && prevY == n) {
a[++prevX][prevY] = k++;
} else if (prevX != 1 && prevY != n) {
if (a[prevX-1][prevY+1] == 0)
{
a[--prevX][++prevY] = k++;
} else {
a[++prevX][prevY] = k++;
}
}
}

for (int i = 1; i <= n; i++)
{
for (int j = 1; j <= n; j++)
{
cout << a[i][j] << " ";
}
cout << endl;
}

return 0;
}
# 模拟

评论

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×