题目描述
zzq很喜欢下国际象棋,一天,他拿着国际象棋中的“马”时突然想到一个问题:
给定两个棋盘上的方格a和b,马从a跳到b最少需要多少步?
现请你编程解决这个问题。
提示:国际象棋棋盘为8格*8格,马的走子规则为,每步棋先横走或直走一格,然后再往外斜走一格。
给定两个棋盘上的方格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
样例输出
题目描述
zzq很喜欢下国际象棋,一天,他拿着国际象棋中的“马”时突然想到一个问题:
给定两个棋盘上的方格a和b,马从a跳到b最少需要多少步?
现请你编程解决这个问题。
提示:国际象棋棋盘为8格*8格,马的走子规则为,每步棋先横走或直走一格,然后再往外斜走一格。
给定两个棋盘上的方格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.
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;
}
#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;
}