UVA 439 骑士的移动 Knight Moves

46 篇文章 1 订阅

骑士的移动 Knight Moves

题面翻译

输入8*8的国际象棋棋盘上的2个格子(列:ah,行:18),求马至少多少步从起点(键盘输入的第一个位置)跳到终点(键盘输入的第二个位置)。

感谢 @陶文祥 提供的翻译。

题目描述

PDF

输入格式

输出格式

样例 #1

样例输入 #1

e2 e4
a1 b2
b2 c3
a1 h8
a1 h7
h8 a1
b1 c3
f6 f6

样例输出 #1

To get from e2 to e4 takes 2 knight moves.
To get from a1 to b2 takes 4 knight moves.
To get from b2 to c3 takes 2 knight moves.
To get from a1 to h8 takes 6 knight moves.
To get from a1 to h7 takes 5 knight moves.
To get from h8 to a1 takes 6 knight moves.
To get from b1 to c3 takes 1 knight moves.
To get from f6 to f6 takes 0 knight moves.

用BFS就行啦~

代码

#include<bits/stdc++.h>

using namespace std;

struct aa{
	
	int x,y;
	
	int ans;
	
}a;

queue <aa> q;

int dx[10]={-1,1,-1,1,-2,2,-2,2};
int dy[10]={-2,2,2,-2,-1,1,1,-1};
	
bool bo[10][10];

int x,y,xx,yy,xxx,yyy;

char ch;

string sx,sy;

int main()
{
	while(cin>>sx)
	{
		cin>>sy;
		
		x=sx[0]-'a'+1;
		y=sx[1]-'0';
		
		xxx=sy[0]-'a'+1;
		yyy=sy[1]-'0';
		
		memset(bo,0,sizeof(bo));
		
		bo[x][y]=1;
		
		q.push( (aa) {x,y,0});
		
		while(q.empty()==0)
		{
			a=q.front();
			q.pop();
			
			if(a.x==xxx&&a.y==yyy)
			{
				cout<<"To get from "<<sx<<" to "<<sy<<" takes "<<a.ans<<" knight moves."<<endl;
				
				break;
			}
			
			for(int i=0;i<=7;i++)
			{
				
				xx=a.x+dx[i];
				yy=a.y+dy[i];
				
				if(xx<=0||yy<=0||xx>8||yy>8)
				{
					continue;
				}
				
				if(bo[xx][yy])
				{
					continue;
				}
				
				bo[xx][yy]=1;
				
				q.push( (aa) {xx,yy,a.ans+1});
				
			}
		}
		
		while(q.empty()==0)
		{
			q.pop();
		}
	}
	
	return 0;
}
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

harmis_yz

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值