UVA 439 - Knight Moves

题目大意:国际象棋,棋盘为8*8的大小,骑士走法为日字走法,如中国象棋的马。问从一个点到另一个点,最少走几步。

解题思路:骑士走的方向有八个,两个方向数组,标记数组也做为步数数组,类似迷宫问题。不详细说了。

ac代码:

#include <iostream>
#include <cstring>
#include <queue>
using namespace std;
char c1, c2;
queue <int> qu;
int n, m, p, q, vis[10][10];
int dx[8] = {-2, -2, 2, 2, -1, 1, -1, 1};
int dy[8] = {-1, 1, -1, 1, -2, -2, 2, 2};
int bfs()
{
	int temp1, temp2, x, y;
	while (!qu.empty())
		qu.pop();
	for (int i=0; i<10; i++)
		memset(vis[i], -1, sizeof(vis[i]));
	vis[p][n] = 0;
	qu.push(p), qu.push(n);
	while (!qu.empty()){
		temp1 = qu.front();
		qu.pop();
		temp2 = qu.front();
		qu.pop();
		if (temp1 == q && temp2 == m)
			return vis[q][m];
		for (int i=0; i<8; i++){
			x = temp1 + dx[i];
			y = temp2 + dy[i];
			if (x >=0 && x < 8 && y >= 0 
			&& y < 8 && vis[x][y] == -1){
				qu.push(x), qu.push(y);
				vis[x][y] = vis[temp1][temp2] + 1;
			}
		}
	}
}
int main()
{
	while (scanf("%c%d %c%d", &c1, &n, &c2, &m)!=EOF){
		p = c1 - 'a', q = c2 - 'a';
		n--, m--;
		printf("To get from %c%d to %c%d", c1, n+1, c2, m+1);
		printf(" takes %d knight moves.\n", bfs());
		getchar();
	}	
return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值