HDU 1372 Knight Moves

题目:http://acm.hdu.edu.cn/showproblem.php?pid=1372

大意:给你一个8*8的棋盘,马从起点到终点的最小步数。。。

 

#include <iostream>
#include <queue>
using namespace std;

struct point
{
int x, y, v;//v是从始点到该点的步数。
};

int g[10][10];
int xx[8] = {1,1,-1,-1,2,2,-2,-2};
int yy[8] = {2,-2,2,-2,1,-1,1,-1};


int main()
{
int i, j;
char a[5], b[5];
int x, y;
point q1, q2;
while (~scanf("%s%s", a, b))
{

memset(g, 0, sizeof(g));//记录有没被遍历过。
queue <point> Q;
//图从0到7开始
//初始化
q1.x = a[0] - 'a';
q1.y = a[1] - '0' - 1;
q1.v = 0;
Q.push(q1);

while (!Q.empty())
{
q2 = Q.front();
Q.pop();
g[q2.x][q2.y] = 1;
if (q2.x == b[0] - 'a' && q2.y == b[1] - '0' - 1)//终点就是最后的队头。
{
break;
}

for (i = 0; i < 8; i++)
{
q1.x = q2.x + xx[i];
q1.y = q2.y + yy[i];
q1.v = q2.v + 1;
if (q1.x >=0 && q1.y >=0 && q1.x < 8 && q1.y < 8 && (!g[q1.x][q1.y]))
{
Q.push(q1);
g[q1.x][q1.y] = 1;
}
}
}

printf("To get from %s to %s takes %d knight moves.\n", a, b, q2.v);

}
return 0;
}

 

posted on 2012-04-03 15:18  [S*I]SImMon_WCG______*  阅读(193)  评论(0编辑  收藏  举报

导航