Buggy Robot
Buggy Robot
有一个机器人在图里,给出初始位置和末位置,图中有障碍的格不能走,同时给出含有4种指令的指令行:上下左右。问最少在指令行中添加或删去多少个指令,使得机器人能走到终点
如果碰到边界或障碍物则不移动
bfs + dp
这个思路的模拟赛的末尾才想出来,debug花了点时间,但是还是没调出来
\(dp[i][j][k] = a\) 表示在位置 \((i, j)\) 的时候,指令走到了第 \(k\) 个的最小代价为 \(a\)
接着就想状态转移
-
添加一个指令:四个方向移动且不使用指令集,转移到 \(dp[xi][yi][k]\)
-
使用指令集:转移到 \(dp[xi][yi][k+1]\)
-
删除一个指令集:转移到 \(dp[x][y][k+1]\)
保证dp的值最小就可以继续搜索
最后的答案是 \(min(\sum_{i=0}^{n}dp[ex][ey][i])\)
\(ex\) 和 \(ey\) 代表终点的坐标,得从 \(0\) 到 \(n\) 搜:指令可以不用或者全用完
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <stack>
#include <queue>
#include <cmath>
#include <vector>
#include <deque>
#include <string>
using namespace std;
typedef long long ll;
const int maxn = 110;
#define pii pair<int, int>
const int inf = 1e5 + 10;
const double eps = 1e-8;
const int xi[4] = { 0, 0, 1, -1 };
const int yi[4] = { 1, -1, 0, 0 };
char dir[4] = { 'R', 'L', 'D', 'U' };
int n, m;
string s;
string gra[maxn];
int dp[maxn][maxn][maxn];
struct node
{
int x, y, v, tp;
node() {}
node(int _x, int _y, int _v, int _tp) { tp = _tp; x = _x; y = _y; v = _v; }
};
bool judge(int x, int y)
{
return x >= 0 && y >= 0 && x < n && y < m;
}
void solve(int sx, int sy, int ex, int ey)
{
for(int i=0; i<n; i++)
for(int j=0; j<m; j++)
for(int k=0; k<=s.length(); k++)
dp[i][j][k] = inf;
queue<node>q;
q.push(node(sx, sy, 0, 0));
while (!q.empty())
{
node now = q.front();
q.pop();
int x = now.x, y = now.y;
if (dp[x][y][now.tp] <= now.v) continue;
dp[x][y][now.tp] = now.v;
bool flag = false;
for (int i = 0; i < 4; i++)
{
int xx = x + xi[i];
int yy = y + yi[i];
if (judge(xx, yy) && gra[xx][yy] != '#')
{
if (dir[i] == s[now.tp]) q.push(node(xx, yy, now.v, now.tp + 1));
q.push(node(xx, yy, now.v + 1, now.tp));
}
else if(dir[i] == s[now.tp]) flag = true;
}
if(flag)
q.push(node(x, y, now.v, now.tp + 1));
else
q.push(node(x, y, now.v + 1, now.tp + 1));
}
}
int main()
{
cin >> n >> m;
for (int i = 0; i < n; i++)
cin >> gra[i];
int sx = 0, sy = 0, ex = 0, ey = 0;
for (int i = 0; i < n; i++)
{
for (int j = 0; j < m; j++)
{
if (gra[i][j] == 'R')
{
sx = i;
sy = j;
}
if (gra[i][j] == 'E')
{
ex = i;
ey = j;
}
}
}
cin >> s;
solve(sx, sy, ex, ey);
int ans = n * m;
for(int i=0; i<=s.length(); i++) ans = dp[ex][ey][i] < ans ? dp[ex][ey][i] : ans;
cout << ans << endl;
return 0;
}