Sample Output
题意是按照马走日的规则 看8*8的数组 从一个位置到一个位置所需的最小步数 广搜 初始位置引出的八个位置存到数列中 然后从第一个开始 第一个出列 再八个进列 知道到达那个位置 输出步数
#include <iostream>
#include<stdio.h>
#include <queue>
#include<string.h>
#include<stdlib.h>
#include<math.h>
using namespace std;
int map[8][8]= {0};
int check(int x,int y)
{
if(x<0||x>7||y<0||y>7||map[x][y]==1)
return 0;
return 1;
}
struct x1
{
int x;
int y;
int step;
} q,next;
int bfs(char (a)[2],char (b)[2])
{
int i,x2,y2,j;
queue<x1> p;
q.x=a[0]-97;
q.y=a[1]-49;
x2=b[0]-97;
y2=b[1]-49;
q.step=0;
for(i=0; i<=7; i++)
for(j=0; j<=7; j++)
map[i][j]=0;
map[q.x][q.y]=1;
while(p.empty()!=1)
p.pop();
p.push(q);
while(p.empty()!=1)
{
q=p.front();
p.pop();
if(q.x==x2&&q.y==y2)
return q.step;
next=q;
next.x=q.x-1;
next.y=q.y-2;
if(check(next.x,next.y)==1)
{
next.step=q.step+1;
map[next.x][next.y]=1;
p.push(next);
}
next.x=q.x-2;
next.y=q.y-1;
if(check(next.x,next.y)==1)
{
next.step=q.step+1;
map[next.x][next.y]=1;
p.push(next);
}
next.x=q.x+2;
next.y=q.y-1;
if(check(next.x,next.y)==1)
{
next.step=q.step+1;
map[next.x][next.y]=1;
p.push(next);
}
next.x=q.x+2;
next.y=q.y+1;
if(check(next.x,next.y)==1)
{
next.step=q.step+1;
map[next.x][next.y]=1;
p.push(next);
}
next.x=q.x-2;
next.y=q.y+1;
if(check(next.x,next.y)==1)
{
next.step=q.step+1;
map[next.x][next.y]=1;
p.push(next);
}
next.x=q.x+1;
next.y=q.y-2;
if(check(next.x,next.y)==1)
{
next.step=q.step+1;
map[next.x][next.y]=1;
p.push(next);
}
next.x=q.x+1;
next.y=q.y+2;
if(check(next.x,next.y)==1)
{
next.step=q.step+1;
map[next.x][next.y]=1;
p.push(next);
}
next.x=q.x-1;
next.y=q.y+2;
if(check(next.x,next.y)==1)
{
next.step=q.step+1;
map[next.x][next.y]=1;
p.push(next);
}
}
return -1;
}
int main()
{
char a[2]= {0},b[2]= {0};
while(~scanf("%c",&a[0]))
{
scanf("%c",&a[1]);
getchar();
scanf("%c",&b[0]);
scanf("%c",&b[1]);
getchar();
printf("To get from %c%c to %c%c takes %d knight moves.\n",a[0],a[1],b[0],b[1],bfs(a,b));
memset(a,0,sizeof(a));
memset(b,0,sizeof(b));
}
return 0;
}
编译错误 呵呵额呵呵呵呵呵