題目鏈接:http://acm.hdu.edu.cn/showproblem.php?pid=1372
簡單的BFS。即給定馬的起點和終點(走的方式和象棋一樣),求最短的路徑。關鍵是要弄清楚馬的行進方向的順序,即從右上第一個順時針過來。
代碼:
</pre><pre name="code" class="cpp"><span style="color:#000000;">#include <iostream>
#include <cstdio>
#include <cstring>
#include <queue>
using namespace std;
int sx,sy,ex,ey,a[10][10],use[10][10];
int dx[8]= {-2,-1,1,2,2,1,-1,-2},dy[8]= {1,2,2,1,-1,-2,-2,-1};
struct point
{
int x,y,step;
};
queue<point> Q;
int bfs(int x,int y)
{
point Start,New;
Start.x=x;
Start.y=y;
Start.step=0;
Q.push(Start);
while(!Q.empty())
{
Start = Q.front();
Q.pop();
if(Start.x==ex&&Start.y==ey)
return Start.step;
for(int i=0; i<8; i++)
{
New.x=Start.x+dx[i];
New.y=Start.y+dy[i];
New.step=Start.step;
if(New.x>0&&New.y>0&&New.x<9&&New.y<9&&!use[New.x][New.y])
{
use[New.x][New.y]=1;
New.step=Start.step+1;
Q.push(New);
}
}
}
}
int main()
{
char S[10],E[10];
while(scanf("%s %s",S,E)!=EOF)
{
while(!Q.empty())
Q.pop();
memset(use,0,sizeof(use));
sx=S[0]-'a'+1,sy=S[1]-'0';
ex=E[0]-'a'+1,ey=E[1]-'0';
use[sx][sy]=1;
printf("To get from %s to %s takes %d knight moves.\n",S,E,bfs(sx,sy));
}
return 0;
}
</span>