简单BFS。就是要把所有的D点当成一个整体考虑(整体移动)。
/* 2531 */
#include <iostream>
#include <queue>
#include <cstdio>
#include <cstring>
#include <cstdlib>
using namespace std; #define MAXN 105 typedef struct {
int x[], y[];
int t;
} node_t; int dn, n, m;
int visit[MAXN][MAXN];
char map[MAXN][MAXN];
node_t beg;
int dir[][] = {
-,,,,,-,,
}; inline bool check(int x, int y) {
return x< || x>=n || y< || y>=m;
} int bfs() {
int i, j, k;
node_t nd, tmp;
queue<node_t> Q;
bool flag, catchQ; memset(visit, 0x3f, sizeof(visit));
visit[beg.x[]][beg.y[]] = beg.t;
Q.push(beg); while (!Q.empty()) {
nd = Q.front();
Q.pop();
tmp.t = nd.t + ;
for (i=; i<; ++i) {
flag = true;
catchQ = false;
for (j=; j<dn; ++j) {
tmp.x[j] = nd.x[j] + dir[i][];
tmp.y[j] = nd.y[j] + dir[i][];
if (check(tmp.x[j], tmp.y[j]) || map[tmp.x[j]][tmp.y[j]]=='O') {
flag = false;
break;
}
if (map[tmp.x[j]][tmp.y[j]] == 'Q') {
catchQ = true;
}
}
if (flag) {
if (catchQ)
return tmp.t;
if (visit[tmp.x[]][tmp.y[]] > tmp.t) {
visit[tmp.x[]][tmp.y[]] = tmp.t;
Q.push(tmp);
}
}
}
} return -;
} int main() {
int i, j, k; #ifndef ONLINE_JUDGE
freopen("data.in", "r", stdin);
freopen("data.out", "w", stdout);
#endif beg.t = ;
while (scanf("%d%d",&n,&m)!=EOF && (n||m)) {
dn = ;
for (i=; i<n; ++i) {
scanf("%s", map[i]);
for (j=; j<m; ++j) {
if (map[i][j] == 'D') {
beg.x[dn] = i;
beg.y[dn] = j;
++dn;
}
}
}
k = bfs();
if (k < )
puts("Impossible");
else
printf("%d\n", k);
} return ;
}