Title Link: http://acm.hdu.edu.cn/showproblem.php?pid=1254
Analysis:
The real move is the box, but there are a few conditions that need to be met to move the box.
1. There is no obstacle in the direction of movement.
2. There are no obstacles behind the box.
3. People can reach the rear of the box. DFS or BFS can be implemented here
Search by criteria.
#include <cstdio>#include<cstring>#include<cmath>#include<iostream>#include<algorithm>#include<queue>#include<cstdlib>#include<stack>#include<vector>#include<Set>#include<map>#defineLL Long Long#defineMoD 1000000007#defineINF 0x3f3f3f3f#defineN 100010using namespaceStd;typedefstructnode{intBx,by; intmx,my; intstep; BOOL operator< (ConstNode &a)Const { returnStep>A.step; }}node;intdx[]={0,0,1,-1};intdy[]={1,-1,0,0};inthash[Ten][Ten][Ten][Ten];intvis[Ten][Ten],s[Ten][Ten];intBx,by,mx,my,nx,ny;intFound,n,m;node Make_node (intAintBintXinty) {Node temp; Temp. Bx=a;temp. by=b; Temp. Mx=x;temp. my=y; Temp.step=0; returntemp;}intJudgeintXinty) { returnx>=0&&x<n&&y>=0&&y<m&&s[x][y]!=1;}voidDfsintNxintNy,intMxintMy) { if(nx==mx&&ny==My) {Found=1;return; } for(intI=0;i<4&&!found;i++) { intx=nx+Dx[i]; inty=ny+Dy[i]; if(Judge (x, y) &&!Vis[x][y]) vis[x][y]=1, DFS (x,y,mx,my); }}voidBFsintBxintBy,intMxintMy) {Priority_queue<node>que; Node p,q; P=Make_node (bx,by,mx,my); Que.push (P); while(!Que.empty ()) {Node P=que.top (); Que.pop (); if(s[p.bx][p.by]==3) {printf ("%d\n", P.step);return; } for(intI=0;i<4; i++) {Q=p; Q.BX=p.bx+dx[i];//where the box movesq.by=p.by+Dy[i]; Nx=p.bx-dx[i];//the rear of the boxny=p.by-Dy[i]; if(Judge (q.bx,q.by) &&judge (nx,ny) &&!Hash[q.bx][q.by][nx][ny]) {memset (Vis,0,sizeof(VIS)); Vis[p.bx][p.by]=vis[nx][ny]=1;//Note that the box here will become a hindrance .Found=0; DFS (nx,ny,p.mx,p.my);//judge whether a person can reach the back of a box if(found) {Hash[q.bx][q.by][nx][ny]=1; Q.mx=p.bx;q.my=p.by;q.step++; Que.push (q); } }}} printf ("-1\n"); return;}voidinit () {memset (hash,0,sizeof(hash)); memset (s),0,sizeof(s)); for(intI=0; i<n;i++) for(intj=0; j<m;j++) {scanf ("%d",&S[i][j]); if(s[i][j]==2) {Bx=i; by=J; } if(s[i][j]==4) {Mx=i; my=J; } }}intMain () {intT; scanf ("%d",&T); while(t--) {scanf ("%d%d",&n,&m); Init (); BFS (bx,by,mx,my); }}
View Code
hdu1254 (BFS+DFS)