跳到正文

题解

题解:B4199 [常州市赛 2020] 旋转数塔

Ashankamiko约 3 分钟
原文
文章信息与版本

文章信息

发布
2025年5月21日
收录
2025年12月12日
更新
2026年11月8日
篇幅
约 3 分钟
获赞
1
题目
B4199

版本

  1. v1当前

题目简述

题意

给定一个正整数 nn,请输出一个矩阵,要求在题目中已经给出。

思路

其实这一题的简化版就是 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

不难看出,特殊转折点的位置分别为:

  • (2,2)(2,2)
  • (3,3)(3,3)
  • (4,4)(4,4)
  • …

所以这一题也就变得简单了,只需要在蛇形方阵代码的基础上加上特判即可。

C++
	if (x == k && y == k)
		f++, k++;

其中,kk 表示特殊转折点的位置,ff 表示方向数组的下标。

AC 代码

C++
#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;
}
原文