Knight Moves
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)Total Submission(s): 6810 Accepted Submission(s): 4107
Of course you know that it is vice versa. So you offer him to write a program that solves the "difficult" part.
Your job is to write a program that takes two squares a and b as input and then determines the number of knight moves on a shortest route from a to b.
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.
Statistic | Submit | Discuss | Note
#include<queue>
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
using namespace std;
int dir[8][2] = { {-1, -2}, {-2, -1}, {-2, 1}, {-1, 2}, {1, 2}, {2, 1}, {2, -1}, {1, -2} };
char mat[10][10];
bool vis[10][10];
struct node
{
int x,y;
int t;
}temp1, temp2;
queue< node >qu;
bool is_legal(int x, int y)
{
if( x < 1 || x > 8 || y < 1 || y > 8)
return false;
return true;
}
int bfs(int sx, int sy, int ex, int ey)
{
memset( vis, 0, sizeof(vis) );
while( !qu.empty() )
qu.pop();
temp1.x = sx;
temp1.y = sy;
temp1.t = 0;
vis[temp1.x][temp1.y] = 1;
qu.push(temp1);
while( !qu.empty() )
{
temp1 = qu.front();
qu.pop();
if(temp1.x == ex && temp1.y == ey)
{
return temp1.t;
}
for(int i = 0; i < 8; i ++)
{
temp2.x = temp1.x + dir[i][0];
temp2.y = temp1.y + dir[i][1];
if( !is_legal(temp2.x, temp2.y) )
continue;
if(vis[temp2.x][temp2.y] == 1)
continue;
vis[temp2.x][temp2.y] = 1;
temp2.t = temp1.t + 1;
qu.push(temp2);
}
}
}
int main()
{
char s[3];
char e[3];
while( ~scanf("%s%s", s, e))
{
int sx = s[0] - 'a' + 1;
int sy = s[1] - '0';
int ex = e[0] - 'a' + 1;
int ey = e[1] - '0';
printf("To get from %s to %s takes %d knight moves.\n", s, e, bfs(sx, sy, ex, ey));
}
return 0;
}
2209



被折叠的 条评论
为什么被折叠?



