POJ 2243 Knight Moves(A*算法)
来源:互联网 发布:sql添加语句 编辑:程序博客网 时间:2024/06/04 00:24
本题题意非常简单,就是给你一个起点和一个终点,按骑士的走法,从起点到终点的最少移动多少次。
可以采用双向广搜或者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
0 0
- POJ 2243 Knight Moves(A*算法)
- POJ 2243 Knight Moves A*
- POJ 2243 - Knight Moves (A*)
- POJ 2243 Knight Moves【A*算法入门演练】
- A*算法. Knight Moves
- POJ 2243 Knight Moves【BFS|A*】
- POJ2243 Knight Moves(A*算法)
- poj 2243 Knight Moves
- POJ 2243 Knight Moves
- poj 2243 Knight Moves
- POJ 2243 Knight Moves
- poj 2243 Knight Moves
- poj 2243 Knight Moves
- poj 2243 Knight Moves
- POJ 2243 Knight Moves
- POJ-2243-Knight Moves
- poj 2243 Knight Moves
- poj 2243:Knight Moves
- Word2010如何从正文开始设置页码
- nyoj_739笨蛋的难题(四)
- JAVA Hibernate工作原理及为什么要用
- PCD(点云数据)文件格式
- 剑指offer 43. n个骰子的点数
- POJ 2243 Knight Moves(A*算法)
- Linux下的IO监控与分析
- linux下shell显示-bash-4.1#不显示路径解决方法
- css3
- Java中List、Set、Map的特点
- 千万不要小看office办公软件应该熟练掌握
- vim不进入窗口进行操作
- session id
- hdu4864(贪心)