http://acm.hdu.edu.cn/showproblem.php?pid=1254
BFS+DFS
我的代码
1 #include <cstdio>
2 #include <cstring>
3 #include <queue>
4 using namespace std;
5 const int N=10;
6 const int dx[4]={0,1,0,-1};
7 const int dy[4]={1,0,-1,0};
8 int maze[N][N],maze2[N][N],vis2[N][N],vis[N][N][N][N];
9 int n,m,flag;
10 struct pos
11 {
12 int x2,y2,x4,y4,dis;
13 };
14 queue<pos> q;
15 void dfs(int x,int y,int ex,int ey)
16 {
17 if (x==ex && y==ey) {flag=1; return;}
18 vis2[x][y]=1;
19 int d,nx,ny;
20 for (d=0;d<4;d++)
21 {
22 nx=x+dx[d]; ny=y+dy[d];
23 if (vis2[nx][ny] || maze2[nx][ny]==1) continue;
24 dfs(nx,ny,ex,ey);
25 if (flag) return;
26 }
27 }
28 int bfs(int x2,int y2,int x4,int y4)
29 {
30 while (!q.empty()) q.pop();
31 vis[x2][y2][x4][y4]=1;
32 pos u={x2,y2,x4,y4,0};
33 q.push(u);
34 while (!q.empty())
35 {
36 u=q.front(); q.pop();
37 x2=u.x2; y2=u.y2; x4=u.x4; y4=u.y4;
38 int dis=u.dis;
39 int d,nx2,ny2,nx4,ny4;
40 for (d=0;d<4;d++)
41 {
42 nx2=x2+dx[d]; ny2=y2+dy[d];
43 nx4=x2; ny4=y2;
44 if (vis[nx2][ny2][nx4][ny4]) continue;
45 if (maze[nx2][ny2]==1) continue;
46 memcpy(maze2,maze,sizeof(maze));
47 maze2[x2][y2]=1; flag=0;
48 memset(vis2,0,sizeof(vis2));
49 if (maze2[x2-dx[d]][y2-dy[d]]!=1)
50 dfs(x4,y4,x2-dx[d],y2-dy[d]);
51 if (!flag) continue;
52 if (maze[nx2][ny2]==3) return dis+1;
53 vis[nx2][ny2][nx4][ny4]=1;
54 pos v={nx2,ny2,nx4,ny4,dis+1};
55 q.push(v);
56 }
57 }
58 return -1;
59 }
60 int main()
61 {
62 int T;
63 scanf("%d",&T);
64 int i,j,x2,y2,x4,y4,ans;
65 while (T--)
66 {
67 memset(vis,0,sizeof(vis));
68 scanf("%d%d",&n,&m);
69 for (i=0;i<=n+1;i++)
70 for (j=0;j<=m+1;j++) maze[i][j]=1;
71 for (i=1;i<=n;i++)
72 for (j=1;j<=m;j++)
73 {
74 int a;
75 scanf("%d",&a);
76 maze[i][j]=a;
77 if (a==2) {x2=i; y2=j;}
78 if (a==4) {x4=i; y4=j;}
79 }
80 ans=bfs(x2,y2,x4,y4);
81 printf("%d\n",ans);
82 }
83 return 0;
84 }