#include<bits/stdc++.h>
using namespace std;
const int N = 105;
const int INF = 0x3f3f3f3f;
int n, m;
int vis[N][N];
int dis[N][N];
const int dir[8][2] = {{-2, 1}, {-2, -1}, {-1, -2}, {-1, 2}, {2, -1}, {2, 1}, {1, -2}, {1, 2}};
struct Node {
int x, y, step;
int g, h, f;
inline bool operator <(const Node &x) const{
return f > x.f;
}
};
Node st, ed;
int Heuristic(const Node &a, const Node &b) {
return (abs(a.x -b.x) + abs(a.y - b.y)) * 10;
} // 曼哈顿(manhattan)估价函数
int A_star()
{
priority_queue<Node> pq;
memset(vis, 0, sizeof vis);
pq.push(st);
while(!pq.empty()) {
Node t;
Node now = pq.top(); pq.pop();
vis[now.x][now.y] = 1;
if(now.x == ed.x && now.y == ed.y) return now.step;
for(int i = 0; i < 8; ++i) {
t.x = now.x + dir[i][0];
t.y = now.y + dir[i][1];
if(t.x >= 0 && t.x < 8 && t.y >= 0 && t.y < 8 && !vis[t.x][t.y]) {
t.g = now.g + 23; // 这里的23表示根号5(即移动一次以后2个点的欧几里得距离) 乘10再取ceil
t.h = Heuristic(t, ed);
t.f = t.g + t.h;
t.step = now.step + 1;
pq.push(t);
}
}
}
return -1;
}
int main()
{
int ans;
char St[3], Ed[3];
while (cin >> St >> Ed)
{
st.x = St[0] - 'a', st.y = St[1] - '1';
ed.x = Ed[0] - 'a', ed.y = Ed[1] - '1';
if (!strcmp(St, Ed))
ans = 0;
else
ans = A_star();
printf("To get from %s to %s takes %d knight moves.\n", St, Ed, ans);
}
return 0;
}
题目来自poj2243,
http://poj.org/problem?id=2243,这里的曼哈顿距离函数和g函数为什么都要乘10呢?