a星算法我不介绍了,参考这个链接http://my.oschina.net/u/211101/blog/126259
直接上这个题目的代码:
#include <iostream> #include <cstring> #include <cstdio> #include <queue> #include <cmath> using namespace std; int dir_x[] = {-2, -1, 1, 2, 2, 1, -1, -2}; int dir_y[] = {1, 2, 2, 1, -1, -2, -2, -1}; const int row = 8; const int col = 8; struct node { int x; int y; int step; int g, h, f; node(){} node(int x, int y, int step, int g, int h, int f):x(x), y(y), step(step), g(g), h(h), f(f){} bool operator < (const node &a) const { return f > a.f; } }; bool vis[row + 2][col + 2]; node start, end; bool judgeSide(const node &tmp) //判断tmp点是否在棋盘上面 { return tmp.x >= 1 && tmp.x <= 8 && tmp.y >= 1 && tmp.y <= 8; } int heuristic(const int &x, const int &y) //启发值 { return (abs(x - end.x) + abs(y - end.y)) * 10; } priority_queue<node> pq; int aStare() { node top, tmp; while(!pq.empty()) { top = pq.top(); pq.pop(); vis[top.x][top.y] = true; if(top.x == end.x && top.y == end.y) return top.step; for(int i = 0; i < 8; i++) { tmp.x = top.x + dir_x[i], tmp.y = top.y + dir_y[i], tmp.step = top.step + 1, tmp.g = top.g + 23, tmp.h = heuristic(tmp.x, tmp.y), tmp.f = tmp.g + tmp.h; if(judgeSide(tmp) && vis[tmp.x][tmp.y] == false) { pq.push(tmp); } } } } int main() { char c1, c2; while(cin >> c1 >> start.y >> c2 >> end.y) { memset(vis, false, sizeof(vis)); while(!pq.empty()) pq.pop(); start.x = c1 - 'a' + 1; start.step = 0; start.g = 0, start.h = heuristic(start.x, start.y), start.f = start.g + start.h; end.x = c2 - 'a' + 1; pq.push(start); int res = aStare(); cout << "To get from " << c1 << start.y << " to " << c2 << end.y << " takes " << res << " knight moves." << endl; } }