您的位置:首页 > 其它

HDU 1372 Knight Moves【BFS】

2014-07-24 15:01 363 查看
题目:http://acm.hdu.edu.cn/showproblem.php?pid=1372

BFS,用来入门不错,配上适合本题的输出路径代码

#include<stdio.h>
#include<queue>
#include<string.h>
using namespace std;
int a[8][2]={{-2,-1},{-2,1},{-1,-2},{-1,2},{1,-2},{1,2},{2,-1},{2,1}},vist[9][9];
typedef struct
{
int x,y,step;
}node;
queue<node> que;
int bfs(node start,node end)
{
int i;
node cur,next;
while( !que.empty() ) que.pop();
que.push(start);
while( !que.empty() )
{
cur=que.front();
que.pop();
for(i=0;i<8;i++)
{
next.x = cur.x + a[i][0];
next.y = cur.y + a[i][1];
next.step = cur.step + 1;
if( !vist[next.x][next.y] && next.x>=1 && next.x<=8 && next.y>=1 && next.y<=8 )
{
vist[ next.x ][ next.y ] = 1;
if(next.x == end.x && next.y == end.y )
return next.step;
que.push(next);
}
}
}
return 0;
}

int main()
{
int move;
char t,m;
node s,e;
while( scanf("%c%d %c%d",&t,&s.y,&m,&e.y) !=EOF)
{
getchar();
memset(vist,0,sizeof(vist));
move = 0;
s.x = t - 'a' + 1;
e.x = m - 'a' + 1;
s.step = 0;
vist[s.x][s.y]=1;
move = bfs(s,e);
printf("To get from %c%d to %c%d takes %d knight moves.\n",t,s.y,m,e.y,move);
}
return 0;
}


输出路径:

void ouput(node last)
{
int i;
node t,save[50];
for(i=move;i>0;i--)
{
t.x=pre[last.x][last.y].x;
t.y=pre[last.x][last.y].y;
save[i].x=t.x,save[i].y=t.y;
last.x=t.x;
last.y=t.y;
}
for(i=1;i<=move;i++)
{
printf("%c%d -> ",save[i].x + 'a' - 1,save[i].y);
}
printf("%c%d\n",e.x + 'a' - 1,e.y);

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: