POJ3278 catch cattle farmer
Enter the location and position of cattle farmer; the farmer has three moves: step forward; step back; position doubled.
Output fastest times to catch the cow
#include<cstdio>
#include<iostream>
#include<cstring>
#include<queue>
#include<algorithm>
using namespace std;
int dis[100005];
void bfs(int stp){
queue <int> q;
q.push(stp);
dis[stp]=0;//标记初始位置步数为0
while(!q.empty())//队列空的时候停止
{
int now=q.front();q.pop();
if(now-1>=0&& now-1 <= 100000 &&dis[now-1]==-1)//走法一
{
dis[now-1]=dis[now]+1;
q.push(now-1);
}
if(now+1>=0&& now+1 <= 100000 &&dis[now+1]==-1)//走法二
{
dis[now+1]=dis[now]+1;
q.push(now+1);
}
if(now*2>=0&& now*2 <= 100000&&dis[now*2]==-1)//走法三
{
dis[now*2]=dis[now]+1;
q.push(now*2);
}
}
}
int main(){
int stp,enp;
cin>>stp>>enp;
memset(dis,-1,sizeof(dis));//dis(距离)定义为-1,标记为没走过
bfs(stp);
cout<<dis[enp]<<endl;
}
int main(){
int stp,enp;
cin>>stp>>enp;
memset(dis,-1,sizeof(dis));
bfs(stp);
cout<<dis[enp]<<endl;
}
HDU1253 Escape
From 0 0 0 o'clock fled a-1 b-1 c-1
Time to enter a time; if the number> step time, output NO
This is a three-dimensional problem of the queue
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<queue>
using namespace std;
int go[6][3]={{0,1,0},{0,-1,0},{0,0,-1},{0,0,1},{1,0,0},{-1,0,0}};//定义走法
int way[50][50][50],dis[50][50][50],time;//way存地图,dis存到该点的步数
int n,a,c,b;
struct node{
int x,y,z;
};
void bfs(){
memset(dis,-1,sizeof(dis));//把所有的步数标记为-1;同时,负数代表没走过
dis[0][0][0]=0;//第一步步数为零
queue<node> Q;//定义队列
node u,next;//u是当前的xyz,next为下一步的xyz
u.x=0;u.y=0;u.z=0;//定义第一步
Q.push(u);//把第一步压入列
while(!Q.empty()){//
node v=Q.front();Q.pop();//提取队列首元素,并把首元素消去
for(int i=0;i<6;i++){//枚举6种走法
next.x=v.x+go[i][0];
next.y=v.y+go[i][1];
next.z=v.z+go[i][2];
if(next.x<0 || next.x>=a || next.y<0 || next.y>=b || way[next.x][next.y][next.z]==1 ||next.z<0 || next.z>=c || dis[next.x][next.y][next.z]!=-1)
continue;//条件不符,重新走
dis[next.x][next.y][next.z]=dis[v.x][v.y][v.z]+1;//步数较上一步+1
Q.push(next);//把下一步加入队列
}
}
}
int main(){
scanf("%d",&n);//
while(n--){
scanf("%d%d%d%d",&c,&a,&b,&time);//输入迷宫大小和time
for(int o=0;o<c;o++)
for(int i=0;i<a;i++)
for(int j=0;j<b;j++)
scanf("%d",&way[i][j][o]);//输入地图
bfs();
if(dis[a-1][b-1][c-1]>time)printf("-1\n");//判断步数和时间
else printf("%d\n",dis[a-1][b-1][c-1]);
}
}