跳到正文

题解

AT_abc387_d [ABC387D] Snaky Walk 题解

lucasincyber约 4 分钟
原文
文章信息与版本

文章信息

发布
2025年1月5日
收录
2025年12月12日
更新
2026年11月8日
篇幅
约 4 分钟

版本

  1. v1当前

题目传送门

思路

bfs 板子题。只需要多记录一维:到达这个格子是从左右来还是从上下来。这样跑 bfs 就不会出错。具体见代码。

代码

C++
#include <bits/stdc++.h>
using namespace std;

const int N = 2005;

struct node
{
	int x, y, f;
};

int h, w, stx, sty, edx, edy;
char mp[N][N];
int dist[N][N];
bool vis[N][N][2]; // 多一维度

bool check(int x, int y, int t)
{
	return (x > 0 && y > 0 && x <= h && y <= w && mp[x][y] != '#' && !vis[x][y][t]);
}

void bfs(int k) // 正常 bfs,加了一个维度
{
	memset(dist, 0x3f, sizeof(dist));
	memset(vis, 0, sizeof(vis));
	queue<node> q;
	q.push({stx, sty, k});
	dist[stx][sty] = 0;
	while (q.size())
	{
		node u = q.front();
		q.pop();
		if (u.x == edx && u.y == edy) break;
		if (vis[u.x][u.y][u.f]) continue;
		vis[u.x][u.y][u.f] = 1;
		int t = u.f;
		t ^= 1;
		if (t == 0)
		{
			if (check(u.x, u.y - 1, t)) q.push({u.x, u.y - 1, t}), dist[u.x][u.y - 1] = min(dist[u.x][u.y - 1], dist[u.x][u.y] + 1);
			if (check(u.x, u.y + 1, t)) q.push({u.x, u.y + 1, t}), dist[u.x][u.y + 1] = min(dist[u.x][u.y + 1], dist[u.x][u.y] + 1);
		}
		else
		{
			if (check(u.x - 1, u.y, t)) q.push({u.x - 1, u.y, t}), dist[u.x - 1][u.y] = min(dist[u.x - 1][u.y], dist[u.x][u.y] + 1);
			if (check(u.x + 1, u.y, t)) q.push({u.x + 1, u.y, t}), dist[u.x + 1][u.y] = min(dist[u.x + 1][u.y], dist[u.x][u.y] + 1);
		}
	}
}

int main()
{
	scanf("%d%d", &h, &w);
	for (int i = 1; i <= h; i++)
	{
		scanf("%s", mp[i] + 1);
		for (int j = 1; j <= w; j++)
		{
			if (mp[i][j] == 'S') stx = i, sty = j;
			else if (mp[i][j] == 'G') edx = i, edy = j;
		}
	}
	bfs(0); // 第一步的两种情况
	int res = 0x3f3f3f3f;
	res = min(res, dist[edx][edy]);
	bfs(1); // 第一步的两种情况
	res = min(res, dist[edx][edy]);
	if (res == 0x3f3f3f3f) printf("-1\n");
	else printf("%d\n", res);
	return 0;
}
原文