跳到正文

题解

题解 P1301 【魔鬼之城】

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

文章信息

发布
2020年7月31日
收录
2026年7月31日
更新
2026年11月8日
篇幅
约 3 分钟
题目
P1301

版本

  1. v1当前

BFS

本题与模板题的区别

  1. 走法,这个题的走法不是固定的,而是根据当前点的值决定
  2. 一个方向不能走两次

如何解决

  1. 其实我们可以发现,不管当前点的值是多少,走法是不变的,变的只是走的步数,所以可以直接将走法先写出来,然后乘上当前点的值就行了
  2. 我们使用一个visvis数组来标记当前点是否走过,从哪个方向走过,也就是多开一维记录当前点被访问的方向。然后再在结构体里加一个prepre变量,用来记录当前点是哪种走法。如果当前点被某种走法走过,或者当前点的走法和上一个点相同,就进行剪枝。注意,这里只用记录上一个点走法的这个剪枝,只会得70分,因为其实某个点可以从多个方向走过来,除了当前点,但是如果只判断方向是否相同,就会默认剪去其它几种走法。
C++
#include <iostream>
#include <cstdio>
using namespace std;
// 注意空间开大点,不然会蜜汁RE
const int N = 1110;
int n, m;
int graph[N][N];
bool vis[N][N][10];
int mv[8][2] = {{1, 0}, {0, 1}, {-1, 0}, {0, -1}, {1, 1}, {1, -1}, {-1, 1}, {-1, -1}};
struct Node {
	int x, y, step, pre;
	Node (int x, int y, int step, int pre) : x(x), y(y), step(step), pre(pre) {};
	Node () {};
} que[N * N];
int bfs() {
	int qtop = 0, qback = 0;
	que[qtop] = Node(1, 1, 0, -1);
	while (qtop <= qback) {
		Node now = que[qtop++];
		if (now.x == n && now.y == m) return now.step;
		int nv = graph[now.x][now.y];
		for (int i = 0; i < 8; i++) {
			// 应该是从当前点偏移,而不是直接走 
			int nx = now.x + mv[i][0] * nv, ny = now.y + mv[i][1] * nv;
			if (nx < 1 || nx > n || ny < 1 || ny > m) continue;
			// 如果下一个点已经以方向i走过一遍了,或者当前走法和上一个点的走法相同,就剪掉 
			if (vis[nx][ny][i] || i == now.pre) continue;
			vis[nx][ny][i] = true;
			que[++qback] = Node(nx, ny, now.step + 1, i);
		}
	}
	return -1;
} 
int main() {
	// 注意行列是反着输入的 
	scanf("%d%d", &m, &n);
	for (int i = 1; i <= n; i++) {
		for (int j = 1; j <= m; j++) {
			scanf("%d", &graph[i][j]);
		}
	}
	int res = bfs();
	if (res == -1) printf("NEVER");
	else printf("%d", res);
	return 0;
}
原文