POJ 2243 Knight Moves(A*算法)
2017-05-03 10:21
225 查看
本题题意非常简单,就是给你一个起点和一个终点,按骑士的走法,从起点到终点的最少移动多少次。
可以采用双向广搜或者A*算法来解决,这里博主选择了采用A*算法来解决。
其中g函数为走到当前状态的经过的步数,启发函数h为当前点到终点的曼哈顿距离,用优先队列保存每个状态按照g+h排序
代码如下
另外给大家推荐一个讲解的A*博客,也是我在学习A*的时候看的博客,希望对大家有所帮助:
http://www.cppblog.com/mythit/archive/2009/04/19/80492.aspx
可以采用双向广搜或者A*算法来解决,这里博主选择了采用A*算法来解决。
其中g函数为走到当前状态的经过的步数,启发函数h为当前点到终点的曼哈顿距离,用优先队列保存每个状态按照g+h排序
代码如下
#include <cstdio> #include <iostream> #include <string> #include <cstring> #include <algorithm> #include <cmath> #include <vector> #include <map> #include <set> #include <stack> #include <queue> using namespace std; struct Knight { int x, y, step; int g, h, f; bool operator <(const Knight &k)const { return f > k.f; } }; bool vis[8][8]; int sx, ex, sy, ey, ans; int dirs[8][2] = { { -2,-1 },{ -2,1 },{ 2,-1 },{ 2,1 },{ -1,-2 },{ -1,2 },{ 1,-2 },{ 1,2 } }; priority_queue<Knight> pq; bool in_map(Knight a) { if (a.x < 0 || a.y < 0 || a.x >= 8 || a.y >= 8) return false; return true; } int get_h(Knight a) { return (abs(a.x - ex) + abs(a.y - ey)); } void Astar() { Knight t, s; while (!pq.empty()) { t = pq.top(); pq.pop(); vis[t.x][t.y] = true; if (t.x == ex&&t.y == ey) { ans = t.step; return; } for (int i = 0;i < 8;i++) { s.x = t.x + dirs[i][0]; s.y = t.y + dirs[i][1]; if (in_map(s) && !vis[s.x][s.y]) { s.g = t.g + 3;//3表示根号5向上取整 s.h = get_h(s); s.f = s.g + s.h; s.step = t.step + 1; pq.push(s); } } } } int main() { std::ios::sync_with_stdio(false); std::cin.tie(0); char a, b; while (~scanf("%c%d %c%d", &a, &sy, &b, &ey)) { getchar(); sx = (a - 'a'); ex = (b - 'a'); sy--; ey--; memset(vis, false, sizeof(vis)); Knight k; k.x = sx; k.y = sy; k.g = k.step = 0; k.h = get_h(k); k.f = k.g + k.h; while (!pq.empty()) pq.pop(); pq.push(k); Astar(); printf("To get from %c%d to %c%d takes %d knight moves.\n", a, sy+1, b, ey+1, ans); } return 0; }
另外给大家推荐一个讲解的A*博客,也是我在学习A*的时候看的博客,希望对大家有所帮助:
http://www.cppblog.com/mythit/archive/2009/04/19/80492.aspx
相关文章推荐
- POJ 2243 Knight Moves【A*算法入门演练】
- POJ2243 Knight Moves(A*算法)
- poj 2243 Knight Moves
- POJ 2243 Knight Moves(启发式搜索)
- POJ 2243 Knight Moves(BFS)
- poj - 2243 Knight Moves
- POJ 2243 Knight Moves(BFS或DFS)
- hdu 1372 || poj 2243 Knight Moves(搜索:BFS+优先队列水题)
- POJ 2243 Knight Moves
- POJ 2243 Knight Moves【BFS|A*】
- poj 1915&&poj 2243 Knight Moves (bfs搜索)
- POJ 2243 - Knight Moves
- poj 2243 Knight Moves
- poj_2243/uva439 Knight Moves(bfs經典)
- POJ 2243 Knight Moves
- POJ 2243 Knight Moves (bfs)
- poj 2243 bfs Knight Moves
- poj 2243 Knight Moves bfs
- UVa 439/HDU 1372/POJ 2243/ZOJ 1091 Knight Moves(BFS&纯数学方法)
- POJ 2243 Knight Moves