其实就是广搜+广搜或者广搜+深搜
真正移动的是箱子,但是要移动箱子需要满足几个条件。
1.移动方向上没有障碍。(废话了……)
2.箱子后方没有障碍。
3.人可以到达箱子后方的地方。
这样就可以写出搜索的条件了
1 #include <stdio.h>
2 #include <string.h>
3 typedef struct{
4 int bX,bY,pX,pY,t;
5 }BOXQUEUE;
6 typedef struct{
7 int x,y;
8 }PEOQUEUE;
9 BOXQUEUE boxQ[1000];
10 PEOQUEUE peoQ[1000];
11 const int dirc[4][2] = {{0,1},{0,-1},{1,0},{-1,0}};
12 int m,n,map[8][8],oBX,oBY;
13 bool visit[8][8],hash[8][8][8][8];
14
15 int canGo(int x,int y){
16 return (x>=0&&y>=0&&x<m&&y<n&&map[x][y]!=1);
17 }
18
19 int peopleCanReach(int strX, int strY, int endX, int endY, int mBX, int mBy){
20 int top,tail,i,nextX,nextY;
21 top = tail = 0;
22 memset(visit,0,sizeof(visit));
23 visit[strX][strY] = true;
24 map[oBX][oBY] = 0;
25 map[mBX][mBy] = 2;
26 peoQ[tail].x = strX;
27 peoQ[tail++].y = strY;
28 while(top < tail){
29 strX = peoQ[top].x;
30 strY = peoQ[top++].y;
31 if(strX == endX && strY == endY){
32 map[mBX][mBy] = 0;
33 map[oBX][oBY] = 2;
34 return 1;
35 }
36 for(i = 0; i < 4; i++){
37 nextX = strX + dirc[i][0];
38 nextY = strY + dirc[i][1];
39 if(canGo(nextX,nextY) && map[nextX][nextY] != 2 && !visit[nextX][nextY]){
40 visit[nextX][nextY] = true;
41 peoQ[tail].x = nextX;
42 peoQ[tail++].y = nextY;
43 }
44 }
45 }
46 map[oBX][oBY] = 2;
47 map[mBX][mBy] = 0;
48 return 0;
49 }
50 int bfs(int bX, int bY, int pX, int pY){
51 int top,tail,i,nextBX,nextBY,nextPX,nextPY,nextT,strT;
52 top = tail = 0;
53 boxQ[tail].bX = bX;
54 boxQ[tail].bY = bY;
55 boxQ[tail].pX = pX;
56 boxQ[tail].pY = pY;
57 boxQ[tail++].t = 0;
58 hash[bX][bY][pX][pY] = true;
59 while(top < tail){
60 bX = boxQ[top].bX;
61 bY = boxQ[top].bY;
62 pX = boxQ[top].pX;
63 pY = boxQ[top].pY;
64 strT = boxQ[top++].t;
65 if(map[bX][bY] == 3)
66 return strT;
67 for(i = 0; i < 4; i++){
68 nextBX = bX + dirc[i][0];
69 nextBY = bY + dirc[i][1];
70 nextPX = bX - dirc[i][0];
71 nextPY = bY - dirc[i][1];
72 nextT = strT + 1;
73 if(canGo(nextBX,nextBY) && canGo(nextPX,nextPY) &&
74 peopleCanReach(pX,pY,nextPX,nextPY,bX,bY)){
75 if(!hash[nextBX][nextBY][nextPX][nextPY]){
76 boxQ[tail].bX = nextBX;
77 boxQ[tail].bY = nextBY;
78 boxQ[tail].pX = nextPX;
79 boxQ[tail].pY = nextPY;
80 boxQ[tail++].t = nextT;
81 hash[nextBX][nextBY][nextPX][nextPY] = true;
82 }
83 }
84 }
85 }
86 return -1;
87 }
88 int main (void){
89 int T,i,j,bX,bY,pX,pY;
90 scanf("%d",&T);
91 while(T--){
92 memset(hash,0,sizeof(hash));
93 scanf("%d%d",&m,&n);
94 for(i = 0; i < m; i++)
95 for(j = 0; j < n; j++){
96 scanf("%d",&map[i][j]);
97 if(map[i][j] == 2){
98 bX = i;
99 bY = j;
100 }
101 else if(map[i][j] == 4){
102 pX = i;
103 pY = j;
104 }
105 }
106 oBX = bX;
107 oBY = bY;
108 printf("%d\n",bfs(bX,bY,pX,pY));
109 }
110 }