例1. hdu 1548
题意
有人想乘电梯从a楼到达b楼,电梯只有两种情况,上和下,给定电梯的上下固定楼,求从a到达b的最少移动次数? -来源HDU1548
每层电梯有一个数字表示该层可以移动的层数
代码
#include<iostream>
#include<cstring>
#include<queue>
#define N 201
using namespace std;
int xx[N],v[N];
int n,a,b;
struct node
{
int step;
int floor;
};
void BFS()
{
node x,y;
queue<node>q;
x.step=0;
x.floor=a;
q.push(x);
v[a]=1;
while(!q.empty())
{
x=q.front();
q.pop();
if(x.floor==b)
{
cout<<x.step<<endl;
return;
}
y.floor=x.floor+xx[x.floor];
y.step=x.step+1;
if(y.floor>0&&y.floor<=n&&!v[y.floor])
{
v[y.floor]=1;
q.push(y);
}
y.floor=x.floor-xx[x.floor];
y.step=x.step+1;
if(y.floor>0&&y.floor<=n&&!v[y.floor])
{
v[y.floor]=1;
q.push(y);
}
}
cout<<-1<<endl;
}
int main()
{
int i;
while(cin>>n>>a>>b&&(n||a||b))
{
memset(v,0,sizeof(v));
for(i=1;i<=n;i++)
{
cin>>xx[i];
}
BFS();
}
return 0;
}
思路:BFS 用队列,用一个数组标记是否到过该层
例2 hdu 1372
象棋里的马从a到达b的最小步数 -来源HDU1372
代码
#include<iostream>
#include<cstring>
#include<queue>
#define N 10
using namespace std;
char map[N][N];
int v[N][N];
int dic[8][2]={1,-2, 2,1, 1,2, -1,-2, -2,1, -2,-1, -1,2, 2,-1};
char q,w,e,r;
int a,s,d,f;
struct node
{
int step;
int n;
int m;
};
void BFS()
{
node x,y;
int i;
queue<node>p;
x.step=0;
x.n=a;
x.m=s;
p.push(x);
v[a][s]=1;
while(!p.empty())
{
x=p.front();
p.pop();
if(x.n==d&&x.m==f)
{
cout<<"To get from ";
cout<<q<<w<<" to "<<e<<r;
cout<<" takes "<<x.step<<" knight moves."<<endl;
return;
}
for(i=0;i<8;i++)
{
y.n=x.n+dic[i][0];
y.m=x.m+dic[i][1];
y.step=x.step+1;
if(y.n>0&&y.n<9&&!v[y.n][y.m]&&y.m>0&&y.m<9)
{
v[y.n][y.m]=1;
p.push(y);
}
}
}
return;
}
int main()
{
int i;
while(cin>>q>>w>>e>>r)
{
a=q+1-'a';
s=w+1-'1';
d=e+1-'a';
f=r+1-'1';
memset(v,0,sizeof(v));
BFS();
}
return 0;
}
思路 BFS 队列 注意马有八个方向