启发式搜索写一写就搞定了,因为不存在障碍物所以每一次走的都必定是最短路中的。
#include <iostream>
#include <string>
#include <cstdio>
#include <algorithm>
#include <vector>
#include <stack>
#include <queue>
#define MAX 100005
#define mod 998244353ll
#define INF 0x3f3f3f3f
#define ll long long
using namespace std;
int cx[] = {0,0,-1,1,-1,1,-1,1};
int cy[] = {-1,1,0,0,-1,1,1,-1};
int sx, sy, ex, ey;
bool vis[10][10];
char str[][10] = { "D","U","L","R","LD","RU","LU","RD" };
struct road {
int x, y;
string str;
friend bool operator<(const road& a, const road& b) {
return abs(a.x - ex) + abs(a.y - ey) > abs(b.x - ex) + abs(b.y - ey);
}
};
int main() {
freopen("a.txt", "r", stdin);
freopen("b.txt", "w", stdout);
string s, e;
cin >> s >> e;
sx = s[0] - 'a';
sy = s[1] - '0' - 1;
ex = e[0] - 'a';
ey = e[1] - '0' - 1;
if (sx == ex && sy == ey) {
cout << 0 << endl;
return 0;
}
priority_queue<road> q;
queue<string> sq;
q.push(road{ sx,sy,"@" });
vis[sx][sy] = true;
bool f = false;
while (!q.empty()) {
road t = q.top();
if (t.str != "@") sq.push(t.str);
q.pop();
for (int i = 0; i < 8; ++i) {
int x0 = t.x + cx[i];
int y0 = t.y + cy[i];
if (x0 < 0 || y0 < 0 || x0 >= 8 || y0 >= 8 || vis[x0][y0]) {
continue;
}
if (x0 == ex && y0 == ey) {
f = true;
cout << sq.size() + 1 << endl;
while (!sq.empty()) {
s = sq.front();
sq.pop();
cout << s << endl;
}
cout << str[i] << endl;
break;
}
vis[x0][y0] = true;
s = str[i];
q.push(road{x0,y0,s});
}
if (f) break;
}
return 0;
}