hdu 1372 Knight Moves 题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1372
题目大意:同样还是跑马数步数(不过千万别以为是和poj1915一样的题啊~)
题目分析:存下起止坐标之后,剩下的就跟poj1915的BFS完全一样了。
code:
#include<cstdio>
#include<cstring>
#include<queue>
using namespace std;
int n=8,dir[8][2]={1,2,-1,2,2,1,2,-1,1,-2,-2,-1,-1,-2,-2,1};
char g[10][10];
struct node
{
int x,y,step;
};
bool judge(int x,int y)
{
return x<n&&y<n&&x>=0&&y>=0&&g[x][y]==0;
}
int bfs(int x,int y,int ex,int ey)
{
queue<node>q;
node first,next;
first.x=x,first.y=y,first.step=0;
q.push(first);
while(!q.empty())
{
first=q.front();
if(first.x==ex&&first.y==ey)return first.step;
q.pop();
g[first.x][first.y]=1;
for(int i=0;i<8;i++)
{
next.x=first.x+dir[i][0];
next.y=first.y+dir[i][1];
if(judge(next.x,next.y))
{
next.step=first.step+1;
q.push(next);
if(next.x==ex&&next.y==ey)return next.step;
g[next.x][next.y]=1;
}
}
}
return -1;
}
int main()
{
int i,j,t,sx,sy,ex,ey,ans;
char s[8];
while(gets(s))
{
memset(g,0,sizeof(g));
sx=s[0]-'a',sy=s[1]-'1',ex=s[3]-'a',ey=s[4]-'1';
ans=bfs(sx,sy,ex,ey);
printf("To get from %c%c to %c%c takes %d knight moves.\n",s[0],s[1],s[3],s[4],ans);
}
return 0;
}
PS:做完poj1915直接转到这道题,想也没想就把代码粘过来了,果断runtime error……