HDU 1254 推箱子

来源:互联网 发布:为什么python安装失败 编辑:程序博客网 时间:2024/06/10 15:56

一个很有意思的 BFS+DFS。附 数据。


本来今天的任务是多重背包,结果为了帮别人找WA点,自己也坑在这道题上了。


最后想了一组自己都没过的数据…发现想法都不对…果断换思路了。


正确思路是以箱子为起点做BFS找最短。每次移动的时候DFS判断人能不能移动到箱子的后面。


开始就我写一个BFS,什么数据都过了。这组过不了

17 40 0 0 00 0 1 00 2 0 31 4 1 01 0 1 01 0 1 01 0 0 0

实际上答案是2.

我写的是总步数最短时,箱子的最短步数。给WA了。


然后我就换思路了,注意状态要用四维,因为可能存在要先把箱子推过去,然后再推回来的情况。


3 6
1 1 1 1 1 1
0 0 0 1 0 0
0 0 2 4 0 3

比如这样。

实际上是5.


#include<cstdio>#include<cstring>#include<string>#include<queue>#include<algorithm>#include<queue>#include<map>#include<stack>#include<iostream>#include<list>#include<set>#include<cmath>#define INF 0x7fffffff#define eps 1e-6using namespace std;int g[8][8];int xx[]={1,-1,0,0};int yy[]={0,0,-1,1};int n,m;struct node{    int x,y,lv;};node box,man,over;bool vis[8][8];bool ok;void dfs(int x1,int y1,int x2,int y2){    if(ok)return;    if(x1==x2&&y1==y2)    {        ok=1;        return;    }    int x,y;    for(int k=0;k<4;k++)    {        x=x1+xx[k];        y=y1+yy[k];        if(x>=n||x<0||y>=m||y<0||g[x][y]==1||vis[x][y])            continue;        vis[x][y]=1;        dfs(x,y,x2,y2);    }}int bfs(){    bool way[8][8][8][8];    queue<node>q;    queue<node>human;    memset(way,0,sizeof(way));    q.push(box);    human.push(man);    way[box.x][box.y][man.x][man.y]=1;    node tmp,now,ma;    while(!q.empty())    {        tmp=q.front();q.pop();        ma=human.front();human.pop();        if(tmp.x==over.x&&tmp.y==over.y)return tmp.lv;        for(int k=0;k<4;k++)        {            int x=tmp.x+xx[k];            int y=tmp.y+yy[k];            if(x>=n||x<0||y>=m||y<0||g[x][y]==1||way[x][y][tmp.x][tmp.y])            continue;            int rex=tmp.x-xx[k];            int rey=tmp.y-yy[k];            if(rex>=n||rex<0||rey>=m||rey<0||g[rex][rey]==1)            continue;            memset(vis,0,sizeof(vis));            ok=0;            vis[tmp.x][tmp.y]=1;            //printf("box %d %d -> %d %d\n",tmp.x,tmp.y,x,y);            //printf("human %d %d -> %d %d\n",ma.x,ma.y,rex,rey);            //system("pause");            dfs(ma.x,ma.y,rex,rey);            if(!ok)            continue;            now.x=x,now.y=y,now.lv=tmp.lv+1;            way[x][y][tmp.x][tmp.y]=1;            q.push(now);            human.push(tmp);        }    }    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",&g[i][j]);            if(g[i][j]==2)                box.x=i,box.y=j,box.lv=0;            else if(g[i][j]==3)                over.x=i,over.y=j;            else if(g[i][j]==4)                man.x=i,man.y=j;        }        int tmp=bfs();        printf("%d\n",tmp);    }}



2 0
原创粉丝点击