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

时间:2023-03-08 19:43:18

题目描述

机器人移动学会(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。

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

输入输出样例

输入样例#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=,M=;
inline int read(){
char c=getchar(); int x=,f=;
while(c<''||c>''){if(c=='-')f=-;c=getchar();}
while(c>=''&&c<=''){x=x*+c-'';c=getchar();}
return x;
}
int n,m,g[N][M],sx,sy,tx,ty,d;char c;
int dx[]={,,,-},dy[]={,,-,}; struct state{
int x,y,dir,c;
state(int a=,int b=,int d=,int cnt=):x(a),y(b),dir(d),c(cnt){}
}st[N*N*];
bool vis[N][N][];
bool check(int x,int y){
for(int i=x;i<=x+;i++)
for(int j=y;j<=y+;j++){
if(i<=||i>n||j<=||j>m) return false;
if(g[i][j]) return false;
}
return true;
} int ans=-,cnt=;
queue<int> q;
void bfs(){
st[++cnt]=state(sx,sy,d);
vis[sx][sy][d]=;
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=;step<=;step++){
if(check(nx=x+dx[d]*step,ny=y+dy[d]*step) && vis[nx][ny][d]==){
st[++cnt]=state(nx,ny,d,c+);
q.push(cnt);
vis[nx][ny][d]=;
//printf("nxy %d %d\n",nx,ny);
}else break;
}
if(vis[x][y][(d+)%]==){
st[++cnt]=state(x,y,(d+)%,c+);
vis[x][y][(d+)%]=;
q.push(cnt);
}
if(vis[x][y][(d-+)%]==){
st[++cnt]=state(x,y,(d-+)%,c+);
vis[x][y][(d-+)%]=;
q.push(cnt);
}
}
}
int main(){
n=read();m=read();
for(int i=;i<=n;i++)
for(int j=;j<=m;j++) g[i][j]=read();
sx=read();sy=read();tx=read();ty=read();
scanf("%c",&c);
if(c=='E') d=;if(c=='S') d=;if(c=='W') d=;if(c=='N') d=; // 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;
}