HDU 1372(BFS)

国际象棋里面的骑士和中国象棋里面的马走法是相同的,走日字。所以如果以一个点为中心的话,可以向外扩散八个方向(也就是说可以走出八种方向不同的日字)。所以只用常规BFS+八个方向的搜索就好辣。

代码如下:

#include <cstdio>
#include <cmath>
#include <cstring>
#include <ctime>
#include <iostream>
#include <algorithm>
#include <set>
#include <vector>
#include <sstream>
#include <queue>
#include <typeinfo>
#include <fstream>
#include <map>
#include <stack>
typedef long long LL;
using namespace std;
int m[10][10];
int re[10][10];
int dr[8][2] = {{-2,-1},{-2,1},{-1,-2},{-1,2},{1,-2},{1,2},{2,-1},{2,1}}; 
struct knight
{
	int x, y, step;
	knight(int x1, int y1, int step1):x(x1), y(y1), step(step1){
	}
};

int bfs(int x, int y, int end_x, int end_y)
{
	queue<knight> q;
	knight s(x, y, 0);
	while (!q.empty())
		q.pop();
	q.push(s);
	while (!q.empty())
	{
		knight temp = q.front();
		q.pop();
		if (temp.x == end_x && temp.y == end_y)
		{
			return temp.step;
		}
		for (int i=0; i<8; i++)
		{
			int t1 = temp.x + dr[i][0];
			int t2 = temp.y + dr[i][1];
			if (t1>=1 && t1 <=8 && t2 >=1 && t2 <= 8 && !re[t1][t2])
			{
				re[t1][t2] = 1;
				knight test(t1, t2, temp.step+1);
				q.push(test);
			}
		}
	}
}
int main()
{
	char a[3], b[3];
	while (scanf("%s", a) != EOF)
	{
		getchar();
		scanf("%s", b);
		memset(re, 0, sizeof(re));
		m[a[1]-48][a[0]-96] = 1;
		m[b[1]-48][b[0]-96] = 1;
		re[a[1]-48][a[0]-96] = 1;
		cout << "To get from " << a << " to " << b << " takes " << bfs(a[1]-48, a[0]-96, b[1]-48, b[0]-96) << " knight moves." << endl;
	}
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值