http://acm.hdu.edu.cn/showproblem.php?pid=2216
BFS
我的代码
1 #include <cstdio>
2 #include <cstring>
3 #include <cstdlib>
4 #include <queue>
5 using namespace std;
6 const int N=25;
7 const int dx[4]={0,1,-1,0};
8 const int dy[4]={1,0,0,-1};
9 char maze[N][N];
10 int vis[N][N][N][N],dis[N][N][N][N];
11 int m,n;
12 struct pos
13 {
14 int zx,zy,sx,sy;
15 };
16 queue<pos> q;
17 int bfs(int zx,int zy,int sx,int sy)
18 {
19 if (abs(zx-sx)+abs(zy-sy)<2) return 0;
20 while (!q.empty()) q.pop();
21 vis[zx][zy][sx][sy]=1; dis[zx][zy][sx][sy]=0;
22 pos u={zx,zy,sx,sy};
23 q.push(u);
24 while (!q.empty())
25 {
26 u=q.front(); q.pop();
27 zx=u.zx; zy=u.zy; sx=u.sx; sy=u.sy;
28 int nzx,nzy,nsx,nsy,d;
29 for (d=0;d<4;d++)
30 {
31 nzx=zx+dx[d]; nzy=zy+dy[d]; nsx=sx-dx[d]; nsy=sy-dy[d];
32 if (maze[nsx][nsy]!='.') {nsx=sx; nsy=sy;}
33 if (maze[nzx][nzy]!='.' || vis[nzx][nzy][nsx][nsy]) continue;
34 vis[nzx][nzy][nsx][nsy]=1;
35 dis[nzx][nzy][nsx][nsy]=dis[zx][zy][sx][sy]+1;
36 if (abs(nzx-nsx)+abs(nzy-nsy)<2) return dis[nzx][nzy][nsx][nsy];
37 pos v={nzx,nzy,nsx,nsy};
38 q.push(v);
39 }
40 }
41 return -1;
42 }
43 int main()
44 {
45 int i,j,zx,zy,sx,sy,ans;
46 while (~scanf("%d%d",&n,&m))
47 {
48 memset(vis,0,sizeof(vis));
49 memset(dis,0,sizeof(dis));
50 memset(maze,0,sizeof(maze));
51 for (i=1;i<=n;i++) scanf("%s",maze[i]+1);
52 for (i=1;i<=n;i++)
53 for (j=1;j<=m;j++)
54 {
55 if (maze[i][j]=='Z') {zx=i; zy=j; maze[i][j]='.';}
56 if (maze[i][j]=='S') {sx=i; sy=j; maze[i][j]='.';}
57 }
58 ans=bfs(zx,zy,sx,sy);
59 if (ans<0) printf("Bad Luck!\n");
60 else printf("%d\n",ans);
61 }
62 return 0;
63 }