poj2243 Knight Moves--A*

原题链接:http://poj.org/problem?id=2243


题意:给定一个起始点和目标点,求按照“日”字走法,最少的步骤。


#define _CRT_SECURE_NO_DEPRECATE 

#include<iostream>
#include<vector>
#include<cstring>
#include<queue>
#include<stack>
#include<algorithm>
#include<cmath>
#define INF 99999999
#define eps 0.0001
using namespace std;

struct Node
{
	int x, y, step;
	int f, g, h;
	bool operator < (const Node & node)const//末尾要加const
	{
		return f > node.f;
	}
};

int dir[8][2] = { { -2,-1 },{ -2,1 },{ 2,-1 },{ 2,1 },{ -1,-2 },{ -1,2 },{ 1,-2 },{ 1,2 } };
int sx, sy;
int dx, dy;
bool vis[10][10];

int getH(const Node & node)
{
	return (abs(sx - node.x) + abs(sy - node.y)) * 10;
}

int aStar(int x, int y)
{
	priority_queue<Node> Q;
	Node cur, nex;
	vis[x][y] = 1;
	cur.x = x;
	cur.y = y;
	cur.step = 0;
	cur.g = 0;
	cur.h = getH(cur);
	cur.f = cur.g + cur.h;
	Q.push(cur);
	while (!Q.empty())
	{
		cur = Q.top();
		Q.pop();
		if (cur.x == dx&&cur.y == dy)
			return cur.step;

		for (int i = 0; i < 8; i++)
		{
			nex.x = dir[i][0] + cur.x;
			nex.y = dir[i][1] + cur.y;
			//if (nex.x >= 1 && nex.x <= 8 && nex.y >= 1 && nex.y <= 7 && !vis[nex.x][nex.y])
			if (nex.x >= 1 && nex.x <= 8 && nex.y >= 1 && nex.y <= 8 && !vis[nex.x][nex.y])
			{
				vis[nex.x][nex.y] = 1;
				nex.step = cur.step + 1;
				nex.g = cur.g + 23;
				nex.h = getH(nex);
				nex.f = nex.g + nex.h;
				Q.push(nex);
			}
		}
	}
	return -1;
}
int main()
{
	char ch1, ch2;
	int t1, t2;
	while (~scanf("%c%d %c%d", &ch1, &t1, &ch2, &t2))
	{
		getchar();
		sx = t1;
		sy = ch1 - 'a' + 1;
		dx = t2;
		dy = ch2 - 'a' + 1;
		
		memset(vis, 0, sizeof(vis));
		printf("To get from %c%d to %c%d takes %d knight moves.\n", ch1, t1, ch2, t2, aStar(sx, sy));
	}
	return 0;
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值