洛谷-P1126 机器人搬重物

洛谷-P1126 机器人搬重物

原题链接:https://www.luogu.com.cn/problem/P1126


题目描述

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

输入格式

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

输出格式

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

img

输入输出样例

输入 #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

C++代码

#include <iostream>
#include <queue>
using namespace std;

struct node {
    int x;
    int y;
    int d;
    int t;
};
int n,m,ex,ey,a[51][51],flag[51][51][4];
int dir[][4]={{-1,0},{0,1},{1,0},{0,-1}};
queue<node> q;

int check(node s) {
    node ns;
    for(int i=1;i<=3;++i) {
        ns.x=s.x+dir[s.d][0]*i;
        ns.y=s.y+dir[s.d][1]*i;
        if(ns.x<1||ns.x>n-1||ns.y<1||ns.y>m-1||a[ns.x][ns.y]
                ||a[ns.x][ns.y+1]||a[ns.x+1][ns.y]||a[ns.x+1][ns.y+1])
            return i-1;
    }
    return 3;
}

int bfs(node s) {
    int i,j;
    node ns;
    q.push(s);
    while(!q.empty()) {
        s=q.front(),q.pop();
        if(s.x==ex&&s.y==ey)
            return s.t;
        if(flag[s.x][s.y][s.d]!=0&&s.t>=flag[s.x][s.y][s.d])
            continue;
        ns.d=s.d,ns.t=s.t+1;
        j=check(s);
        for(i=1;i<=j;++i) {
            ns.x=s.x+dir[s.d][0]*i;
            ns.y=s.y+dir[s.d][1]*i;
            q.push(ns);
        }
        ns.x=s.x,ns.y=s.y;
        ns.d=(s.d+3)%4;
        q.push(ns);
        ns.d=(s.d+1)%4;
        q.push(ns);
        flag[s.x][s.y][s.d]=s.t;
    }
    return -1;
}

int main() {
    int i,j;
    char sd;
    node s;
    cin>>n>>m;
    for(i=1;i<=n;++i)
        for(j=1;j<=m;++j)
            cin>>a[i][j];
    cin>>s.x>>s.y>>ex>>ey>>sd;
    switch(sd) {
    case 'N': s.d=0;break;
    case 'E': s.d=1;break;
    case 'S': s.d=2;break;
    case 'W': s.d=3;break;
    }
    s.t=0;
    cout<<bfs(s)<<endl;
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/yuzec/p/12899865.html