您的位置:首页 > 其它

洛谷P1126机器人搬重物[BFS]

2016-08-12 15:38 246 查看

题目描述

机器人移动学会(RMI)现在正尝试用机器人搬运物品。机器人的形状是一个直径1.6米的球。在试验阶段,机器人被用于在一个储藏室中搬运货物。储藏室是一个N*M的网格,有些格子为不可移动的障碍。机器人的中心总是在格点上,当然,机器人必须在最短的时间内把物品搬运到指定的地方。机器人接受的指令有:向前移动1步(Creep);向前移动2步(Walk);向前移动3步(Run);向左转(Left);向右转(Right)。每个指令所需要的时间为1秒。请你计算一下机器人完成任务所需的最少时间。

输入输出格式

输入格式:

输入的第一行为两个正整数N,M(N,M<=50),下面N行是储藏室的构造,0表示无障碍,1表示有障碍,数字之间用一个空格隔开。接着一行有四个整数和一个大写字母,分别为起始点和目标点左上角网格的行与列,起始时的面对方向(东E,南S,西W,北N),数与数,数与字母之间均用一个空格隔开。终点的面向方向是任意的。

输出格式:

一个整数,表示机器人完成任务所需的最少时间。如果无法到达,输出-1。



输入输出样例

输入样例#1:

9 10
0 0 0 0 0 0 1 0 0 0
0 0 0 0 0 0 0 0 1 0
0 0 0 1 0 0 0 0 0 0
0 0 1 0 0 0 0 0 0 0
0 0 0 0 0 0 1 0 0 0
0 0 0 0 0 1 0 0 0 0
0 0 0 1 1 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
1 0 0 0 0 0 0 0 1 0
7 2 2 7 S


输出样例#1:

12

---------------------------------------------------------------------------------------------------------

典型迷宫问题,BFS求解

注意要一次要判四个点可以走到(无障碍,不出界),并且走好几步时路径上的某点走不到也不行;

封装一个结构体比较方便

一定要vis啊好多次忘了

有一个点没过,不知道为什么

#include<iostream>
#include<cstdio>
#include<queue>
using namespace std;
const int N=55,M=55;
inline int read(){
char c=getchar(); int x=0,f=1;
while(c<'0'||c>'9'){if(c=='-')f=-1;c=getchar();}
while(c>='0'&&c<='9'){x=x*10+c-'0';c=getchar();}
return x;
}
int n,m,g
[M],sx,sy,tx,ty,d;char c;
int dx[4]={0,1,0,-1},dy[4]={1,0,-1,0};

struct state{
int x,y,dir,c;
state(int a=0,int b=0,int d=0,int cnt=0):x(a),y(b),dir(d),c(cnt){}
}st[N*N*4];
bool vis

[4];
bool check(int x,int y){
for(int i=x;i<=x+1;i++)
for(int j=y;j<=y+1;j++){
if(i<=0||i>n||j<=0||j>m) return false;
if(g[i][j]) return false;
}
return true;
}

int ans=-1,cnt=0;
queue<int> q;
void bfs(){
st[++cnt]=state(sx,sy,d);
vis[sx][sy][d]=1;
q.push(cnt);
while(!q.empty()){//printf("%d\n",cnt);
state now=st[q.front()]; q.pop();
int x=now.x,y=now.y,d=now.dir,c=now.c,nx,ny;
if(x==tx&&y==ty) {ans=c;break;}//printf("xy %d %d %d %d\n",x,y,d,c);

for(int step=1;step<=3;step++){
if(check(nx=x+dx[d]*step,ny=y+dy[d]*step) && vis[nx][ny][d]==0){
st[++cnt]=state(nx,ny,d,c+1);
q.push(cnt);
vis[nx][ny][d]=1;
//printf("nxy %d %d\n",nx,ny);
}else break;
}
if(vis[x][y][(d+1)%4]==0){
st[++cnt]=state(x,y,(d+1)%4,c+1);
vis[x][y][(d+1)%4]=1;
q.push(cnt);
}
if(vis[x][y][(d-1+4)%4]==0){
st[++cnt]=state(x,y,(d-1+4)%4,c+1);
vis[x][y][(d-1+4)%4]=1;
q.push(cnt);
}
}
}
int main(){
n=read();m=read();
for(int i=1;i<=n;i++)
for(int j=1;j<=m;j++) g[i][j]=read();
sx=read();sy=read();tx=read();ty=read();
scanf("%c",&c);
if(c=='E') d=0;if(c=='S') d=1;if(c=='W') d=2;if(c=='N') d=3;

//    for(int i=1;i<=n;i++)
//        for(int j=1;j<=m;j++) cout<<g[i][j]<<" ";
//    if(check(sx,sy)==false) cout<<-1;
bfs();
cout<<ans;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: