http://acm.hdu.edu.cn/showproblem.php?pid=2612
2次bfs
我的代码
1 #include <cstdio>
2 #include <cstring>
3 #include <queue>
4 using namespace std;
5 const int N=210,INF=1000000;
6 const int dx[4]={0,1,0,-1};
7 const int dy[4]={1,0,-1,0};
8 char maze[N][N];
9 int vis[N][N][2],dis[N][N][2];
10 int n,m;
11 struct coor
12 {
13 int x,y;
14 };
15 queue<coor> q;
16 void bfs(int x,int y,int c)
17 {
18 while (!q.empty()) q.pop();
19 coor u={x,y};
20 vis[x][y][c]=1; dis[x][y][c]=0;
21 q.push(u);
22 while (!q.empty())
23 {
24 u=q.front(); q.pop();
25 x=u.x; y=u.y;
26 int d,nx,ny;
27 for (d=0;d<4;d++)
28 {
29 nx=x+dx[d]; ny=y+dy[d];
30 if (maze[nx][ny]=='#' || !maze[nx][ny] || vis[nx][ny][c]) continue;
31 vis[nx][ny][c]=1; dis[nx][ny][c]=dis[x][y][c]+1;
32 coor v={nx,ny};
33 q.push(v);
34 }
35 }
36 }
37 int main()
38 {
39 int i,j,yx,yy,mx,my;
40 while (~scanf("%d%d",&n,&m))
41 {
42 for (i=1;i<=n;i++) scanf("%s",maze[i]+1);
43 for (i=1;i<=n;i++)
44 for (j=1;j<=m;j++)
45 {
46 if (maze[i][j]=='Y') {yx=i; yy=j;}
47 if (maze[i][j]=='M') {mx=i; my=j;}
48 }
49 memset(vis,0,sizeof(vis));
50 memset(dis,0,sizeof(dis));
51 bfs(yx,yy,0);
52 bfs(mx,my,1);
53 int min=INF;
54 for (i=1;i<=n;i++)
55 for (j=1;j<=m;j++)
56 if (maze[i][j]=='@' && vis[i][j][0] && vis[i][j][1] && dis[i][j][0]+dis[i][j][1]<min)
57 min=dis[i][j][0]+dis[i][j][1];
58 min*=11;
59 printf("%d\n",min);
60 }
61 return 0;
62 }