1 #include<stdio.h>
2 #include<string.h>
3 #include<queue>
4 using namespace std;
5 int xx[4]={0,0,1,-1};
6 int yy[4]={1,-1,0,0};
7 int used[125][125],hash[125][125],sum,n,m;
8 char map[125][125];
9 struct dian
10 {
11 int x[30],y[30],step;
12 };
13 queue<dian>q;
14 int bfs()
15 {
16 dian n1,n2;
17 int i,j,judge;
18 while (!q.empty())
19 {
20 n1=q.front(); q.pop();
21 // for (i=1;i<=sum;i++) printf("%d %d ",n1.x[i],n1.y[i]);
22 // printf("%d\n",n1.step);
23 for (i=1;i<=sum;i++)
24 if (hash[n1.x[i]][n1.y[i]]==1) return(n1.step);
25 for (i=0;i<4;i++)
26 {
27 judge=0;
28 for (j=1;j<=sum;j++)
29 {
30 n2.x[j]=n1.x[j]+xx[i];
31 n2.y[j]=n1.y[j]+yy[i];
32 n2.step=n1.step+1;
33 // if (hash[n2.x[j]][n2.y[j]]==1) return(n2.step);
34 if (n2.x[j]<0||n2.x[j]>=n||n2.y[j]<0||n2.y[j]>=m||map[n2.x[j]][n2.y[j]]=='O'||used[n2.x[1]][n2.y[1]]==1)
35 { judge=-100000; break; }
36 // if (used[n2.x[j]][n2.y[j]]==1) judge++;
37 }
38 if (judge<0) continue;
39 used[n2.x[1]][n2.y[1]]=1;
40 q.push(n2);
41 }
42 }
43 return -1;
44 }
45 int main()
46 {
47 int i,j,t;
48 dian n1;
49 while (~scanf("%d%d",&n,&m)&&(n!=0&&m!=0))
50 {
51 getchar(); sum=0;
52 memset(used,0,sizeof(used));
53 memset(hash,0,sizeof(hash));
54 while (!q.empty()) q.pop();
55 for (i=0;i<n;i++) scanf("%s",map[i]);
56 for (i=0;i<n;i++)
57 for (j=0;j<m;j++)
58 if (map[i][j]=='D')
59 {
60 sum++; n1.x[sum]=i; n1.y[sum]=j;
61 }
62 else if (map[i][j]=='Q') hash[i][j]=1;
63 used[n1.x[1]][n1.y[1]]=1;
64 n1.step=0; q.push(n1);
65 t=bfs();
66 if (t==-1) printf("Impossible\n");
67 else printf("%d\n",t);
68 }
69 return 0;
70 }
http://acm.hdu.edu.cn/showproblem.php?pid=2531