http://acm.hdu.edu.cn/showproblem.php?pid=1254

暴搜,状态是四维的(箱子和人的坐标),向一个方向推箱子还要判断人能否走到推的位置,1A

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

int n, m;
int tx, ty;
int vis[8][8][8][8],vis1[8][8];
int M[8][8];

struct node {
    int x, y, px, py, step;
    node() {};
    node(int x, int y, int px, int py, int step) :
        x(x), y(y), px(px), py(py), step(step) {
        };
};

node st;

int dx[]={1,-1,0,0};
int dy[]={0,0,1,-1};

struct point {
    int x, y;
    point(int x, int y) :
        x(x), y(y) {
        };
};

int bfs1(int x, int y, int px, int py) {
    queue <point> q;
    q.push(point(px, py));
    while(!q.empty()) {
        point u = q.front();
        q.pop();
        if(u.x == x && u.y == y) return 1;
        for(int i = 0; i < 4; i++){
            int xx = u.x + dx[i];
            int yy = u.y + dy[i];
            if(xx < 0 || yy < 0 || xx >=n || yy >= m) continue ;
            if(M[xx][yy] == 1 || vis1[xx][yy]) continue;
            vis1[xx][yy] = 1;
            q.push(point(xx, yy));
        }
    }
    return 0;
};

int bfs2() {
    queue <node> q;
    memset(vis, 0, sizeof(vis));
    q.push(st);
    vis[st.x][st.y][st.px][st.py] = 1;
    while(!q.empty()) {
        node u = q.front();
        q.pop();
        if(u.x == tx && u.y == ty) return u.step;
        for(int i = 0; i < 4; i++) {
            int xx = u.x + dx[i];
            int yy = u.y + dy[i];
            int px = u.x - dx[i];
            int py = u.y - dy[i];
            if(xx < 0 || yy < 0 || xx >= n || yy >=m || px < 0 || py < 0 || px >= n || py >= m) continue;
            if(M[xx][yy] == 1 || M[px][py] == 1) continue;
            if(vis[xx][yy][px][py]) continue;
            memset(vis1, 0, sizeof(vis1));
            vis1[u.x][u.y] = 1;
            int flag = bfs1(px, py, u.px, u.py);
            vis1[u.x][u.y] = 0;
            if(flag) {
                vis[xx][yy][px][py] = 1;
                q.push(node(xx, yy, px, py, u.step + 1));
            }
        }
    }
    return -1;
};

int main() {
    int T;
    scanf("%d", &T);
    while(T--) {
        scanf("%d%d", &n, &m);
        for(int i = 0; i < n; i++) {
                for(int j = 0; j < m; j++) {
                    scanf("%d", &M[i][j]);
                }
        }
        for(int i = 0; i < n; i++) {
            for(int j = 0; j < m; j++) {
                if(M[i][j] == 3)
                    tx = i, ty = j;
                if(M[i][j] == 2)
                    st.x = i, st.y = j;
                if(M[i][j] == 4)
                    st.px = i, st.py = j;
            }
        }
        st.step = 0;
        printf("%d\n", bfs2());
    }
    return 0;
}
View Code