D题:Loong and Takahashi
标签:模拟
题意:给定奇数
n
n
n,完成蛇形填数。
(
n
<
=
45
)
(n<=45)
(n<=45)
举个例子:
n
=
5
n=5
n=5
1 2 3 4 5
16 17 18 19 6
15 24 T 20 7
14 23 22 21 8
13 12 11 10 9
题解:蛇形填数 经典题,最中间改成
T
T
T。轮流往四个方向填数,跑到边界或者已经填过数的位置停止。
代码:
#include <bits/stdc++.h>
using namespace std;
int a[55][55];
int main() {
int n, c = 1, x = 0, y = 0;
cin >> n;
a[0][0] = 1;
while (c < n * n) {
while (y + 1 < n && !a[x][y + 1]) a[x][++y] = ++c; // 右
while (x + 1 < n && !a[x + 1][y]) a[++x][y] = ++c; // 下
while (y - 1 >= 0 && !a[x][y - 1]) a[x][--y] = ++c; // 左
while (x - 1 >= 0 && !a[x - 1][y]) a[--x][y] = ++c; // 上
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (i == n / 2 && j == n / 2) {
cout << "T ";
continue;
}
cout << a[i][j] << " ";
}
cout << endl;
}
return 0;
}