题意 机器人走迷宫,按给定指令,求更改最小指令。
建图,跑dj
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef double db;
const int maxn = 50*50*100;
const int inf = 0x3f3f3f3f3f;
char mp[51][51], s[51];
int x1[5] = {1, 0, -1, 0};
int y1[5] = {0, 1, 0, -1};
int n, m;
int cnt, head[maxn], dis[maxn],vis[maxn];
struct edge {
int v, w, next;
bool operator < (const edge &a) const {
return w > a.w;
}
} e[maxn*5];
void dj(int s) {
priority_queue<edge> q;
dis[s] = 0;
q.push((edge){s, 0});
while (!q.empty()) {
edge tmp = q.top(); q.pop();
if (vis[tmp.v]) continue;
vis[tmp.v] = 1;
for (int i = head[tmp.v]; ~i; i = e[i].next) {
edge u = e[i];
if (dis[u.v] > dis[tmp.v] + u.w) {
dis[u.v] = dis[tmp.v] + u.w;
q.push((edge){u.v, dis[u.v]});
}
}
}
}
void add(int u, int v, int co) {
e[cnt].v = v;
e[cnt].w = co;
e[cnt].next = head[u];
head[u] = cnt++;
}
bool judge(int x, int y) {
if(x<=0||x>n||y<=0||y>m||mp[x][y]=='#')
return false;
return true;
}
int main() {
cin >> n >> m;
memset(head, -1, sizeof(head));
cnt = 0;
for (int i = 1; i <= n; i++)
scanf("%s", mp[i] + 1);
scanf("%s", s+1);
int len = strlen(s + 1);
int st, ed;
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= m; j++) {
if (mp[i][j] == 'R') st = ((i - 1) * m + j)*(len+1);
if (mp[i][j] == 'E') ed = ((i - 1) * m + j)*(len+1);
if (mp[i][j] == '#') continue;
for (int k = 1; k <= len; k++) {
for (int p = 0; p < 4; p++) {
int x = i + x1[p];
int y = j + y1[p];
if (judge(x, y)) {
int u = ((i - 1) * m + j) * (len + 1) + k;
int v = ((x - 1) * m + y) * (len + 1) + k;
add(u, v, 1);
}
}
int x = i, y = j;
if(s[k] == 'R') y++;
if(s[k] == 'L') y--;
if(s[k] == 'D') x++;
if(s[k] == 'U') x--;
if(judge(x, y)) {
int u = ((i - 1) * m + j) * (len + 1) + k;
int v = ((x - 1) * m + y) * (len + 1) + k + 1;
add(u, v, 0);
}
else {
int u = ((i - 1) * m + j) * (len + 1) + k;
add(u, u + 1, 0);
}
int u = ((i - 1) * m + j) * (len + 1) + k;
add(u, u + 1, 1);
}
for (int p = 0; p < 4; p++) {
int x = i + x1[p];
int y = j + y1[p];
if (judge(x, y)) {
int u = ((i - 1) * m + j) * (len + 1) + len + 1;
int v = ((x - 1) * m + y) * (len + 1) + len + 1;
add(u, v, 1);
}
}
}
}
for (int i = 1; i <= (n * m + 1) * (len + 1); i++)
dis[i] = inf;
dj(st + 1);
int ans = inf;
for (int i = 1; i <= len + 1; i++) {
int tmp = ed + i;
ans = min(ans, dis[tmp]);
}
cout << ans << endl;
return 0;
}