马的移动问题(国际象棋BFS)

问题 F: 马的移动

题目描述

zzq很喜欢下国际象棋,一天,他拿着国际象棋中的“马”时突然想到一个问题:
给定两个棋盘上的方格a和b,马从a跳到b最少需要多少步?
现请你编程解决这个问题。

提示:国际象棋棋盘为8格*8格,马的走子规则为,每步棋先横走或直走一格,然后再往外斜走一格。

输入

输入包含多组测试数据。每组输入由两个方格组成,每个方格包含一个小写字母(a~h),表示棋盘的列号,和一个整数(1~8),表示棋盘的行号。

输出

对于每组输入,输出一行“To get from xx to yy takes n knight moves.”。

样例输入

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

样例输出

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.
 
题意概括:国际象棋中,给出马的起始位置和欲到达位置,求出到达最短的步数。 
解题思路:这是一道简单的广搜问题,根据起始的位置,可以知道下一步可以走的八个位置,进行搜索,中间判断,不能走到原来的位置,还有就是不能跳到棋盘的外面去了,然后一步步搜索,直到找到最终位置就可以了。
程序源代码:
#include<stdio.h>
#include<string.h>
int x,y,x1,y1;
int b[10][10];
int c[8][2]={1,2,1,-2,-1,2,-1,-2,2,1,2,-1,-2,1,-2,-1};
int min=9999;
void fun(int x0,int y0,int step)
{
	if(x0==x1&&y0==y1)
	 {
	   if(min>step)
	    min=step;
	   return ;
	     }
	int x2,y2;
	if(step>min)
	 return ; 
	for(int i=0;i<8;i++)
	{
		x2=x0+c[i][0];
		y2=y0+c[i][1];
		if(x2>8||x2<1||y2<1||y2>8)
		 continue;
		if(b[x2][y2]==0)
	    {
		 b[x2][y2]=1;
	     fun(x2,y2,step+1);
	     b[x2][y2]=0;
		 }
	}
	return ;	
}
int main()
{
	int i,j,k,m,n;
	char s0,s1;
	while(scanf("%c%d",&s0,&y)!=EOF)
	{
		getchar();
		min=9999;
		scanf("%c%d",&s1,&y1);
		memset(b,0,sizeof(b));
		x=s0-'a'+1;
		x1=s1-'a'+1;
		b[x][y]==1;
		fun(x,y,0);
	    printf("To get from %c%d to %c%d takes %d knight moves.\n",s0,y,s1,y1,min);
	    getchar();
	}
	return 0;
} 

 

 

 

  • 1
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值