同样是BFS过的,注意骑士走的方法就可以了
Code
#include <iostream>
#include <queue>
using namespace std;
struct node
{
int x,y;
int step;
};
int sx,sy,ex,ey,moves,chess[10][10];
int dir[8][2] = {{2,1},{-2,1},{1,2},{1,-2},{2,-1},{-2,-1},{-1,2},{-1,-2}};
void BFS()
{
moves=-1;
queue<node> q;
node n,p;
n.x = sx;
n.y = sy;
n.step=0;
q.push(n);
chess[sx][sy] = 1;
while(!q.empty())
{
n = q.front();
q.pop();
if(n.x == ex && n.y == ey)
{
moves=n.step;
break;
}
for(int i = 0;i < 8;i++)
{
int tx = n.x + dir[i][0];
int ty = n.y + dir[i][1];
if(tx >= 0 && tx < 8 && ty >= 0 && ty < 8 && !chess[tx][ty])
{
p.x = tx;
p.y = ty;
p.step=n.step+1;
q.push(p);
chess[tx][ty] = 1;
}
}
}
}
int main()
{
char c,a[30],b[30];
int i;
//freopen("1.txt","r",stdin);
while(scanf("%s %s",&a,&b) == 2)
{
moves = 0;
if(strcmp(a,b) == 0)
printf("To get from %s to %s takes %d knight moves.\n",a,b,moves);
else
{
sscanf(a,"%c%d",&c,&sy);
sx = c - 'a';
sy--;
sscanf(b,"%c%d",&c,&ey);
ex = c - 'a';
ey--;
memset(chess,0,sizeof(chess));
BFS();
printf("To get from %s to %s takes %d knight moves.\n",a,b,moves);
}
}
return 0;
}
#include <iostream>
#include <queue>
using namespace std;
struct node
{
int x,y;
int step;
};
int sx,sy,ex,ey,moves,chess[10][10];
int dir[8][2] = {{2,1},{-2,1},{1,2},{1,-2},{2,-1},{-2,-1},{-1,2},{-1,-2}};
void BFS()
{
moves=-1;
queue<node> q;
node n,p;
n.x = sx;
n.y = sy;
n.step=0;
q.push(n);
chess[sx][sy] = 1;
while(!q.empty())
{
n = q.front();
q.pop();
if(n.x == ex && n.y == ey)
{
moves=n.step;
break;
}
for(int i = 0;i < 8;i++)
{
int tx = n.x + dir[i][0];
int ty = n.y + dir[i][1];
if(tx >= 0 && tx < 8 && ty >= 0 && ty < 8 && !chess[tx][ty])
{
p.x = tx;
p.y = ty;
p.step=n.step+1;
q.push(p);
chess[tx][ty] = 1;
}
}
}
}
int main()
{
char c,a[30],b[30];
int i;
//freopen("1.txt","r",stdin);
while(scanf("%s %s",&a,&b) == 2)
{
moves = 0;
if(strcmp(a,b) == 0)
printf("To get from %s to %s takes %d knight moves.\n",a,b,moves);
else
{
sscanf(a,"%c%d",&c,&sy);
sx = c - 'a';
sy--;
sscanf(b,"%c%d",&c,&ey);
ex = c - 'a';
ey--;
memset(chess,0,sizeof(chess));
BFS();
printf("To get from %s to %s takes %d knight moves.\n",a,b,moves);
}
}
return 0;
}