hdu1372 BFS求最短路径长度
Posted 当蜗牛有了理想
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了hdu1372 BFS求最短路径长度相关的知识,希望对你有一定的参考价值。
Crawling in process... Crawling failed Time Limit:1000MS Memory Limit:65536KB 64bit IO Format:%I64d & %I64u
Description
Of course you know that it is vice versa. So you offer him to write a program that solves the "difficult" part.
Your job is to write a program that takes two squares a and b as input and then determines the number of knight moves on a shortest route from a to b.
Input
Output
Sample Input
e2 e4 a1 b2 b2 c3 a1 h8 a1 h7 h8 a1 b1 c3 f6 f6
Sample Output To get from e2 to e4 takes 2 knight moves. To get from a1 to b2 takes 4 knight moves. To get from b2 to c3 takes 2 knight moves. To get from a1 to h8 takes 6 knight moves. To get from a1 to h7 takes 5 knight moves. To get from h8 to a1 takes 6 knight moves. To get from b1 to c3 takes 1 knight moves. To get from f6 to f6 takes 0 knight moves.
代码:
/*
简单BFS,寻找最短路径长度
*/
#include <iostream>
#include <queue>
#include <stack>
#include <algorithm>
#include <queue>
#include <stack>
#include <cmath>
#include <cstring>
#include <cstdio>
using namespace std;
const double eps=1e-8;
const double pi=acos(-1.0);
int m[10][10];//用来标记,避免重复,bfs常见剪枝
int ax,ay,bx,by;
struct nod
{
int x,y;
int step;
};
int f[8][2]={{-2,1},{-2,-1},{-1,2},{-1,-2},{1,2},{1,-2},{2,1},{2,-1}};
queue<nod> q;
int ans;
void bfs()
{
nod t;
while(!q.empty())
{
t=q.front();
m[t.x][t.y]=1;
q.pop();
if(t.x==bx&&t.y==by)
{
ans=t.step;
return;
}
for(int i=0;i<8;i++)
{
int xx=t.x+f[i][0];
int yy=t.y+f[i][1];
nod n;
n.x=xx,n.y=yy,n.step=t.step+1;
if(xx>=1&&xx<=8&&yy>=1&&yy<=8&&!m[xx][yy])
q.push(n);
}
}
}
int main()
{
char a,c;
int b,d;
while(scanf("%c%d %c%d",&a,&b,&c,&d)!=EOF)//输入的时候需要注意,如果一个一个输入,中间加空格,也可以用两个字符串格式化输入(空格截止)
{
getchar();
memset(m,0,sizeof(m));
ax=b,ay=a-‘a‘+1;
bx=d,by=c-‘a‘+1;//sb的我重复定义
//cout<<ax<<" "<<ay<<" "<<bx<<" "<<by<<endl;
nod k;
k.x=ax,k.y=ay,k.step=0;
q.push(k);
bfs();
cout<<"To get from "<<a<<b<<" to "<<c<<d<<" takes "<<ans<<" knight moves."<<endl;
while(!q.empty())
q.pop();//对于有多组数据情况,一定要记得清空队列
}
return 0;
}
以上是关于hdu1372 BFS求最短路径长度的主要内容,如果未能解决你的问题,请参考以下文章