UVa1601 The Morning after Halloween

116 篇文章 1 订阅
53 篇文章 1 订阅

【写在最前】
  本题应该是双向BFS的最基本的题目,但是我还是看了题解,某种程度上还是抄了代码,其实抛开本题的双向BFS不说,本题的预处理就值得我们竖起大拇指了,好好理解
【一点解释】
  当BFS的状态总数是nm的时候,双向BFS的状态总数nm/2 就能够搜索到答案了

You are working for an amusement park as an operator of an obakeyashiki, or a haunted house, in
which guests walk through narrow and dark corridors. The house is proud of their lively ghosts, which
are actually robots remotely controlled by the operator, hiding here and there in the corridors. One
morning, you found that the ghosts are not in the positions where they are supposed to be. Ah,
yesterday was Halloween. Believe or not, paranormal spirits have moved them around the corridors in
the night. You have to move them into their right positions before guests come. Your manager is eager
to know how long it takes to restore the ghosts.
In this problem, you are asked to write a program that, given a floor map of a house, finds the
smallest number of steps to move all ghosts to the positions where they are supposed to be.
A floor consists of a matrix of square cells. A cell is either a wall cell where ghosts cannot move
into or a corridor cell where they can.
At each step, you can move any number of ghosts simultaneously. Every ghost can either stay in
the current cell, or move to one of the corridor cells in its 4-neighborhood (i.e. immediately left, right,
up or down), if the ghosts satisfy the following conditions:

  1. No more than one ghost occupies one position at the end of the step.
  2. No pair of ghosts exchange their positions one another in the step.
    For example, suppose ghosts are located as shown in the following (partial) map, where a sharp
    sign (‘#’) represents a wall cell and ‘a’, ‘b’, and ‘c’ ghosts.

ab#
#c##

The following four maps show the only possible positions of the ghosts after one step.

#### ####

ab# a b# acb# ab #
#c## #c## # ## #c##

#### ####

Input
The input consists of at most 10 datasets, each of which represents a floor map of a house. The format
of a dataset is as follows.
w h n
c11 c12 . . . c1w
c21 c22 . . . c2w
.
.
.
.
.
.
.
.
.
.
.
.
ch1 ch2 . . . chw
w, h and n in the first line are integers, separated by a space. w and h are the floor width and height
of the house, respectively. n is the number of ghosts. They satisfy the following constraints.
4 ≤ w ≤ 16, 4 ≤ h ≤ 16, 1 ≤ n ≤ 3
Subsequent h lines of w characters are the floor map. Each of cij is either:
• a ‘#’ representing a wall cell,
• a lowercase letter representing a corridor cell which is the initial position of a ghost,
• an uppercase letter representing a corridor cell which is the position where the ghost corresponding
to its lowercase letter is supposed to be, or
• a space representing a corridor cell that is none of the above.
In each map, each of the first n letters from a and the first n letters from A appears once and only
once. Outermost cells of a map are walls; i.e. all characters of the first and last lines are sharps; and the
first and last characters on each line are also sharps. All corridor cells in a map are connected; i.e. given
a corridor cell, you can reach any other corridor cell by following corridor cells in the 4-neighborhoods.
Similarly, all wall cells are connected. Any 2 × 2 area on any map has at least one sharp. You can
assume that every map has a sequence of moves of ghosts that restores all ghosts to the positions where
they are supposed to be.
The last dataset is followed by a line containing three zeros separated by a space.
Output
For each dataset in the input, one line containing the smallest number of steps to restore ghosts into
the positions where they are supposed to be should be output. An output line should not contain extra
characters such as spaces.
Sample Input
5 5 2

#A#B#

#b#a#

16 4 3
################

##########

ABCcba

################
16 16 3
################

## #

# ## # c#

## ########b#

## # # #

# ## # #

a# # # #

## #### ##

# # #

##### # ##

#B# #

C# #

# # #######

###### A##

#

################
0 0 0
Sample Output
7
36
77

【题意翻译】
w h (w, h <= 16)的网格有 n ( n <= 3) 个小写字母(代表鬼)其余的是‘#’(代表障碍格) 或 ‘ ’(代表空格。 要求把他们移动到对应的大写字母里。每步可以有多少个鬼同时移动(均为上下左右4个移动方向之一), 但每步移动两个鬼不能占用同一个位置, 也不能在一步之内交换位置。输入保证空格联通,障碍联通,且在2 2子网格中至少有一个障碍格,并且最外面一层是障碍格。输入保证有解。
【题目分析】

抛开双向BFS,这个题的预处理也很值得学习。节点个数太多1616=256,并且有三个鬼,所以状态总数几乎是 256^3,不管是时间还是空间,肯定都要炸,所以就要把状态算的精确一些,省去一些不可能的情况,首先最外层都是’#’,这样这个图就变成了最大 14 * 14 = 196,还是有点大,注意题目条件,每22中至少有一个障碍,所以这196个点至多有75%是空格,196*0.75 = 147。这就差不多了,由于后面可能有加点的操作,不过最多加2个点,也就是说总数不会超过150,这个数字就比较理想了,时间上和空间上都不错。判重的问题,刚才分析过了,每个鬼能够出现的格子数目不超过150,八位二进制数就能表示(2^8 == 256),因此三个就可以用24位二进制数表示,和int还有一段距离,所以 转换成一个int型整数判重 是再好不过的了。将所有空格连接起来用的是类似邻接表的操作。

之后就是双向BFS的模板了,两个队列,分别入队出发点和终点,vis数组肯定是三维的,只是原来的0、1变成了现在的0、1、2,因为要区分是在哪一边扩展的过程中遍历到的这个点。当一个点在两个队列中都出现了,就说明找到了,返回dis的和,别忘了+1.还有一个需要注意的是双向BFS每次扩展一层而不是扩展一个节点。

// 单向BFS代码
// Created by DELL on 2020/2/20.   740ms
//双向BFS 例题   题目对我来说还是不简单的,  先来一遍单向的代码
//abc分别是三个鬼的位置  把三个鬼的位置压成一个二进制数 来存储状态

#include <iostream>
#include <cstring>
#include <cstdio>
#include <algorithm>
#include <queue>
#define Maxn 150
#define Maxs 20
using namespace std;
char maps[Maxs][Maxs];
int n,m,cnt,sum,s[5],t[5];
int deg[Maxn],G[Maxn][Maxn];
int x[Maxn],y[Maxn],id[Maxn][Maxn];
int dist[Maxn][Maxn][Maxn];
int dx[] = {0,0,0,-1,1};
int dy[] = {0,1,-1,0,0};
inline int ID(int a,int b,int c) { return (a << 16) | (b << 8) | c; }
inline bool conflict(int a,int b,int a2,int b2) {
    if((a2 == b && b2 == a) || a2 == b2) return true; // 交换 或者 相撞
    return false;
}
int BFS() {
    queue<int> q;
    dist[s[0]][s[1]][s[2]] = 0;
    q.push(ID(s[0],s[1],s[2]));
    while(!q.empty()) {
        int top = q.front(); q.pop();
        int a =(top >> 16) & 0xff,b = (top >> 8) & 0xff,c = (top & 0xff);
        if(a == t[0] && b == t[1] && c == t[2]) return dist[a][b][c];
        for(int i=0; i<deg[a]; i++) {
            int a2 = G[a][i];
            for(int j=0; j<deg[b]; j++) {
                int b2 = G[b][j];
                if(conflict(a,b,a2,b2)) continue;
                for(int k=0; k<deg[c]; k++) {
                    int c2 = G[c][k];
                    if(dist[a2][b2][c2] != -1) continue;
                    if(conflict(a,c,a2,c2)) continue;
                    if(conflict(b,c,b2,c2)) continue;
                    q.push(ID(a2,b2,c2));
                    dist[a2][b2][c2] = dist[a][b][c] + 1;
                }
            }
        }
    }
    return -1;
}

int main(int argc,char* argv[]) {
    while(scanf("%d%d%d\n",&m,&n,&sum) == 3 && m) {
        cnt = 0;
        memset(dist,-1,sizeof(dist));
        for(int i=0; i<n; i++) fgets(maps[i],Maxs,stdin);
        for(int i=0; i<n; i++)
            for(int j=0; j<m; j++)
                if(maps[i][j] != '#'){
                    x[cnt] = i,y[cnt] = j,id[i][j] = cnt;
                    if(islower(maps[i][j])) s[maps[i][j] - 'a'] = cnt;
                    else if(isupper(maps[i][j])) t[maps[i][j] - 'A'] = cnt;
                    cnt++;
                }
        for(int i=0; i<cnt; i++) {
            int X = x[i],Y = y[i];
            deg[i] = 0;
            for(int k=0; k<5; k++)  {// 四个方向
                int xx = X + dx[k],yy = Y + dy[k];
                if(maps[xx][yy] != '#') G[i][deg[i]++] = id[xx][yy];
            }
        }
        if(sum <= 2) {
            s[2] = t[2] = G[cnt][0] = cnt;//
            deg[cnt++] = 1;
        }
        if(sum <= 1) {
            s[1] = t[1] = G[cnt][0] = cnt;
            deg[cnt++] = 1;
        }
        printf("%d\n",BFS());
    }
}

// 双向BFS代码 560ms
// Created by DELL on 2020/2/20.
// &表示按位与,只有两个位同时为1,才能得到1
// 0xff 表示255(二进制表示为 1111 1111)  &0xff 只是为了取得最低八位
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <queue>
#define Maxn 150
#define Maxs 20
using namespace std;
int n,m,sum,s[5],t[5];
int x[Maxn],y[Maxn],id[Maxn][Maxn],map[Maxn][Maxn];
int num[Maxn],dist[Maxn][Maxn][Maxn],vis[Maxn][Maxn][Maxn];
int dx[] = {0,0,0,1,-1};
int dy[] = {0,1,-1,0,0};
inline int Make_ID(int a,int b,int c) { return (a<<16)|(b<<8)|c; }

inline bool IS_Conflict(int a,int b,int a2,int b2) {
    if((a == b2 && a2 == b) || (a2 == b2)) return true;
    return false;
}

int BFS() {
    queue<int> que,fque;
    dist[s[0]][s[1]][s[2]] = 0;
    dist[t[0]][t[1]][t[2]] = 1;
    vis[s[0]][s[1]][s[2]] = 1;
    vis[t[0]][t[1]][t[2]] = 2;
    que.push(Make_ID(s[0],s[1],s[2]));
    fque.push(Make_ID(t[0],t[1],t[2]));
    while(!que.empty() && !fque.empty()) {
        int Num = que.size(),fnum = fque.size();// 每次扩展一层状态  不是一个状态  单向BFS里我其实写的每次扩展一个 实则是不对的
        while(Num--) {
            int top = que.front(); que.pop();
            int a = (top >> 16) & 0xff,b = (top >> 8) & 0xff,c = top & 0xff;
            for(int i=0; i<num[a]; i++) {
                int a2 = map[a][i];
                for(int j=0; j<num[b]; j++) {
                    int b2 = map[b][j];
                    if(IS_Conflict(a,b,a2,b2)) continue;
                    for(int k=0; k<num[c]; k++){
                        int c2 = map[c][k];
                        if(IS_Conflict(a,c,a2,c2)) continue;
                        if(IS_Conflict(b,c,b2,c2)) continue;
                        if(vis[a2][b2][c2] == 0) {
                            que.push(Make_ID(a2,b2,c2));
                            vis[a2][b2][c2] = 1;
                            dist[a2][b2][c2] = dist[a][b][c] + 1;
                        }
                        else if(vis[a2][b2][c2] == 2) { return dist[a2][b2][c2] + dist[a][b][c]; }
                    }
                }
            }
        }
        while(fnum--) {
            int top = fque.front(); fque.pop();
            int a = (top >> 16),b = (top >> 8) & 0xff,c = top & 0xff;
            for(int i=0; i<num[a]; i++) {
                int a2 = map[a][i];
                for(int j=0; j<num[b]; j++) {
                    int b2 = map[b][j];
                    if(IS_Conflict(a,b,a2,b2)) continue;
                    for(int k=0; k<num[c]; k++){
                        int c2 = map[c][k];
                        if(IS_Conflict(a,c,a2,c2)) continue;
                        if(IS_Conflict(b,c,b2,c2)) continue;
                        if(vis[a2][b2][c2] == 0) {
                            fque.push(Make_ID(a2,b2,c2));
                            vis[a2][b2][c2] = 2;
                            dist[a2][b2][c2] = dist[a][b][c] + 1;
                        }
                        else if(vis[a2][b2][c2] == 1) { return dist[a2][b2][c2] + dist[a][b][c]; }
                    }
                }
            }
        }
    }
    return -1;
}

int main(int argc,char* argv[]) {
    char maps[Maxs][Maxs]; int cnt = 0;
    while(scanf("%d%d%d\n",&m,&n,&sum) == 3 && m ){
    	cnt = 0; 
        memset(dist,-1,sizeof(dist));
        memset(vis,0,sizeof(vis));
        for(int i=0; i<n; i++) fgets(maps[i],Maxs,stdin);
        for(int i=0; i<n; i++)
            for(int j=0; j<m; j++)
                if(maps[i][j] != '#'){
                    x[cnt] = i,y[cnt] = j,id[i][j] = cnt;
                    if(islower(maps[i][j])) s[maps[i][j] - 'a'] = cnt;
                    else if(isupper(maps[i][j])) t[maps[i][j] - 'A'] = cnt;
                    cnt ++;
                }
        for(int i=0; i<cnt; i++) {
            num[i] = 0;
            for(int k=0; k<5; k++)
                if(maps[x[i] + dx[k]][y[i] + dy[k]] != '#') map[i][num[i] ++] = id[x[i] + dx[k]][y[i] + dy[k]];
        }
        if(sum <= 2) {
            s[2] = t[2] = map[cnt][0] = cnt;
            num[cnt++] = 1;
        }
        if(sum <= 1) {
            s[1] = t[1] = map[cnt][0] = cnt;
            num[cnt++] = 1;
        }
        printf("%d\n",BFS());
    }
    return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

七情六欲·

学生党不容易~

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值