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

来源:互联网 发布:农村淘宝怎么开店 编辑:程序博客网 时间:2024/06/04 18:45

问题 F: 马的移动

时间限制: 1 Sec  内存限制: 32 MB
提交: 6  解决: 6
[提交][状态][讨论版]

题目描述

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

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

输入

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

输出

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

样例输入

e2 e4a1 b2b2 c3a1 h8a1 h7h8 a1b1 c3f6 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;} 


原创粉丝点击