博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
UVA439 knightMoves (A*启发搜索)
阅读量:4610 次
发布时间:2019-06-09

本文共 1662 字,大约阅读时间需要 5 分钟。

第一个A*,纪念下。

A*要保证最短路一定要估价函数小于等于实际值,越接近越好

估价函数取Manhattan距离除以二。

//Rey
#include
#include
#include
#include
using namespace std;const int N = 8;bool C[N][N];struct node{ int g,h; int x, y; bool operator < (const node& rhs) const{ if(g + h > rhs.g + rhs.h) return true; if(g + h < rhs.h + rhs.g ) return false; return g > rhs.g; }};int tax,tay;inline void getH(node& o){ o.h = (abs(o.x-tax)+abs(o.y-tay))>>1;}#define joinC(n) C[n.x][n.y] = trueint dx[] = {
1,2, 1, 2,-1,-2,-1,-2};int dy[] = {
2,1,-2,-1,-2,-1, 2, 1};int bfs(node &start){ priority_queue
Q; memset(C,false,sizeof(C)); Q.push(start); joinC(start); node cur,nxt; int i,nx,ny; while(Q.size()){ cur = Q.top();Q.pop(); if(cur.x == tax && cur.y == tay) return cur.g; for(i = 0; i < N; i++){ nx = cur.x + dx[i]; ny = cur.y + dy[i]; if(nx >= N || nx < 0 || ny >= N || ny < 0 || C[nx][ny]) continue; nxt.x = nx ; nxt.y = ny; nxt.g = cur.g+1 ; getH(nxt); joinC(nxt); Q.push(nxt); } } return -1;}int main(){ node start; char fro[3],to[3]; char ch; int n; while(~scanf("%s",fro)){ scanf("%s",to); sscanf(fro,"%c",&ch); sscanf(fro+1,"%1d",&n); start.x = ch -'a'; start.y = n-1; start.g = 0; sscanf(to,"%c",&ch); sscanf(to+1,"%1d",&n); tax = ch - 'a'; tay = n-1; getH(start); printf("To get from %s to %s takes %d knight moves.\n",fro,to,bfs(start)); } return 0;}

 

转载于:https://www.cnblogs.com/jerryRey/p/4597277.html

你可能感兴趣的文章
回溯法算法框架
查看>>
残差学习【转载】
查看>>
0302 关于IT行业的就业感想
查看>>
3、流程语句相关练习
查看>>
30、git 使用
查看>>
iOS网络-02-数据解析(JSON与XML)
查看>>
python列表求和的几种等效电路
查看>>
Luogu P3393 逃离僵尸岛
查看>>
Flatten Binary Tree to Linked List
查看>>
Edit Distance
查看>>
软件工程第一次作业补充
查看>>
N76E003---输入捕获
查看>>
poj 1094 Sorting It All Out(拓扑排序)
查看>>
acdream B - 郭式树 (水题 卡cin,cout, 卡LL)
查看>>
BMP图像格式
查看>>
python的匿名函数lambda解释及用法
查看>>
c#遍历Dictionary使用KeyValuePair
查看>>
defineProperties属性的运用==数据绑定
查看>>
关于 IOS 发布的点点滴滴记录(一)
查看>>
《EMCAScript6入门》读书笔记——14.Promise对象
查看>>