题目简述
题意
给定一个正整数 ,请输出一个矩阵,要求在题目中已经给出。
思路
其实这一题的简化版就是 P5731 蛇形方阵。
其思路类似于 dfs,只是 dfs 的路线必须要严格控制,唯一的难点就是如何控制 dfs 的线路。
观察下列正确的矩阵,从中找出规律,注意观察特殊的转折点的位置。
1 2 3 4 5 6 7 8 9 10
36 37 64 63 62 61 60 59 58 11
35 38 65 66 67 68 69 70 57 12
34 39 84 85 96 95 94 71 56 13
33 40 83 86 97 98 93 72 55 14
32 41 82 87100 99 92 73 54 15
31 42 81 88 89 90 91 74 53 16
30 43 80 79 78 77 76 75 52 17
29 44 45 46 47 48 49 50 51 18
28 27 26 25 24 23 22 21 20 19不难看出,特殊转折点的位置分别为:
- …
所以这一题也就变得简单了,只需要在蛇形方阵代码的基础上加上特判即可。
if (x == k && y == k)
f++, k++;其中, 表示特殊转折点的位置, 表示方向数组的下标。
AC 代码
#include <bits/stdc++.h>
using namespace std;
#define in cin
#define out cout
int dx[4] = {0, -1, 0, 1}, dy[4] = {1, 0, -1, 0}, n, a[55][55], m = 1, k = 2;
void dfs(int x, int y, int f) { //dfs,注意控制线路
a[x][y] = m++;
if (x == k && y == k) //特殊转折
f++, k++;
f %= 4;
for (int i = 0; i < 4; i++) { //遍历处理
int tx = dx[f % 4] + x, ty = y + dy[f % 4];
if (tx > 0 && tx <= n && ty <= n && ty > 0 && a[tx][ty] == 0) {
dfs(tx, ty, f);
return;
} else
f++;
}
}
int main() {
in >> n;
dfs(1, 1, 0);
for (int i = 1; i <= n; i++) { //输出矩阵
for (int j = 1; j <= n; j++)
out << a[i][j] << ' ';
out << endl;
}
return 0;
}