您的位置:首页 > 其它

UVA 439 Knight Moves

2016-02-27 18:15 274 查看
题意:8*8的棋盘,给定一个起点和终点,求马至少需要多少步可以从起点跳到终点。

思路:bfs模板。注意坐标判重,判断坐标越界。

#include <iostream>
#include <cstdio>
#include <cstring>
#include <queue>
using namespace std;
#define Clean(x,y) memset(x,y,sizeof(x))
const int dx[8] = {-2,-2,-1,-1,1,1,2,2};
const int dy[8] = {1,-1,2,-2,2,-2,1,-1};

int st_x,st_y,ed_x,ed_y;
bool flag[10][10];
char temp[20];
int main()
{
while( gets(temp) )
{
queue<int> step,x,y;
st_x = temp[0] - 'a' + 1;
ed_x = temp[3] - 'a' + 1;
st_y = temp[1] - '0';
ed_y = temp[4] - '0';
Clean(flag,true);
flag[st_x][st_y]  = false;
x.push(st_x);
y.push(st_y);
step.push(0);
int tx,ty,xx,yy,ss;
while( !x.empty() )
{
xx = x.front();
yy = y.front();
ss = step.front();
x.pop();
y.pop();
step.pop();
if ( xx == ed_x && yy == ed_y )
{
printf("To get from %c%c to %c%c takes %d knight moves.\n",temp[0],temp[1],temp[3],temp[4],ss);
break;
}
for(int i = 0; i < 8; i++ )
{
tx = xx + dx[i];
ty = yy + dy[i];
if (  tx>=1 && tx<=8 && ty>=1 && ty<=8 && flag[tx][ty] )
{
flag[tx][ty] = false;
x.push(tx);
y.push(ty);
step.push(ss+1);
}
}
}
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: