Problem: 2243 | User: nasta | |
Memory: 564K | Time: 125MS | |
Language: G++ | Result: Accepted |
国际象棋里的马(knight)是走“日”字的,给你任意两个坐标,问你最少走几步能走到。
解法:
BFS
#include <cstdio>
#include <cstring>
//#include <fstream>
#include <queue>
#define SIZE 8
using namespace std;
int s[SIZE][SIZE];
int d[SIZE][SIZE];
int dir[8][2] = {{-1, -2}, {-2, -1}, {1, 2}, {2, 1}, {-1, 2}, {1, -2}, {-2, 1}, {2, -1}};
struct point{
int x, y;
};
int bfs(int sx, int sy, int dx, int dy)
{
memset(s, 0, sizeof(int)*SIZE*SIZE);
memset(d, 255, sizeof(int)*SIZE*SIZE);
s[sx][sy] = 1;
d[sx][sy] = 0;
queue<point> q;
point t;
t.x = sx;
t.y = sy;
q.push(t);
while(!q.empty())
{
point u;
u = q.front();
q.pop();
for(int i=0; i<8; ++i)
{
point v;
v.x = u.x + dir[i][0];
v.y = u.y + dir[i][1];
if(s[v.x][v.y] == 0 && v.x == dx && v.y == dy)
return d[u.x][u.y]+1;
if(v.x >= 0 && v.x <8 && v.y >= 0 && v.y <8)
{
if(s[v.x][v.y] == 0)
{
s[v.x][v.y] = 1;
d[v.x][v.y] = d[u.x][u.y]+1;
q.push(v);
}
}
}
s[u.x][u.y] = 2;
}
return d[dx][dy];
}
int main()
{
//freopen("in.txt", "rb+", stdin);
char s[3], d[3];
s[2]=0;
d[2]=0;
while(scanf("%c%c %c%c\n", s, s+1, d, d+1) == 4)
{
int step = bfs(s[0]-'a', s[1]-'1', d[0]-'a', d[1]-'1');
printf("To get from %s to %s takes %d knight moves.\n", s, d, step);
}
//fclose(stdin);
return 0;
}