跳到正文

题解

题解:AT_abc453_d [ABC453D] Go Straight

__LCT__约 5 分钟
原文

这是 2026年4月13日 存档的第 1 版,不是当前版本。查看当前版本

文章信息与版本

文章信息

收录
2026年4月13日
更新
2026年4月13日
篇幅
约 5 分钟

版本

  1. v2当前
  2. v1

写一篇题解纪念我 AtCoder 上棕。

难度方面,建议下位绿,有一定码量的搜索。

分析

首先先考虑没有 o 和 x 的情况。那么就是一个 bfs 板子,每一个节点记录其前驱节点,从起点跑一遍广搜即可。

接着,我们需要考虑 o 和 x 的约束。解决这个约束很简单,状态不够维数来凑嘛!所以直接多开一维记录来到这里的方向,然后就可以根据来的方向决策下一格了。

由于我使用的是 bfs,所以得到的路径长度必定是在这个状态下最短的,所以从任意一个可以到达的状态往回找路径都可以。

接下来,这里对于“前驱”的定义需要改一下,对于这一个节点,我们已经可以通过到达这里的方向来找到上一个格子的位置了。所以,我们只需要记录到上一个格子走的方向,然后就可以拼出来路径了。

这道题到这里都只有黄的难度,但是一看代码你就知道有绿了。为了让大家简化一下代码,不要写出 100100 多行的东西,我提一下实现建议:

其实 .,S,x,o 这四种格子是可以揉在一起写的,采取不同的跳过循环策略就可以了。

然后,在方向数组之外存一个顺序相同的字符数组,表示上下左右,然后直接使用方向获取字符会使得代码变短很多。

最后写出来 8787 行:

C++
#include <bits/stdc++.h>
#define endl '\n'
using namespace std;

const int INF = 0x3f3f3f3f;
const int N = 1000 + 5;

char f[5] = "UDLR", s[N][N];
int mv[4][2] = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
int h, w, sx, sy, fx, fy;
int pre[N][N][4];
bool vis[N][N][4];
struct Node
{
	int x, y, dir;
	Node() : x(0), y(0), dir(0) {}
	Node(int _x, int _y, int _d) : x(_x), y(_y), dir(_d) {}
}; 
queue<Node> q;

void bfs(int x, int y)
{
	q.push(Node(x, y, 0)), q.push(Node(x, y, 1));
	q.push(Node(x, y, 2)), q.push(Node(x, y, 3));
	vis[x][y][0] = vis[x][y][1] = vis[x][y][2] = vis[x][y][3] = true;
	while(!q.empty())
	{
		Node u = q.front();
		q.pop();
		if(s[u.x][u.y] == '.' || s[u.x][u.y] == 'x' || s[u.x][u.y] == 'S' || s[u.x][u.y] == 'o')
		{
			for(int i = 0; i < 4; i ++ )
			{
				if(s[u.x][u.y] == 'x' && i == u.dir) continue;
				if(s[u.x][u.y] == 'o' && i != u.dir) continue;
				int dx = u.x + mv[i][0], dy = u.y + mv[i][1];
				if(dx > 0 && dy > 0 && dx <= h && dy <= w && s[dx][dy] != '#' && !vis[dx][dy][i])
				{
					vis[dx][dy][i] = true;
					pre[dx][dy][i] = u.dir;
					q.push(Node(dx, dy, i));
				}
			}
		}
		else if(s[u.x][u.y] == 'G') return;
	}
}

vector<char> stps;

int main()
{
	ios :: sync_with_stdio(0);
	cin.tie(0); cout.tie(0);
	cin >> h >> w;
	for(int i = 1; i <= h; i ++ )
	{
		for(int j = 1; j <= w; j ++ )
		{
			cin >> s[i][j];
			if(s[i][j] == 'S') sx = i, sy = j;
			if(s[i][j] == 'G') fx = i, fy = j;
		}
	}
	bfs(sx, sy);
	int nx = fx, ny = fy, ndir = 4;
	if(vis[fx][fy][0]) ndir = 0;
	else if(vis[fx][fy][1]) ndir = 1;
	else if(vis[fx][fy][2]) ndir = 2;
	else if(vis[fx][fy][3]) ndir = 3;
	if(ndir == 4)
	{
		cout << "No";
		return 0;
	}
	cout << "Yes" << endl;
	while(nx != sx || ny != sy)
	{ 
		stps.push_back(f[ndir]);
		int nxdir = pre[nx][ny][ndir];
		nx = nx - mv[ndir][0], ny = ny - mv[ndir][1];
		ndir = nxdir;
	}
	reverse(stps.begin(), stps.end());
	for(char c : stps) cout << c;
	return 0;
}