以左上角坐标 为参考。
每次移动要判断整个身体所在的位置 是否满足可移动 条件
/*
*problem ID: HDU 2531
* Author ID: fuqiang11
* TIME: 2013-07-20
* Algorithm: 搜索 BFS
* Status: (Accept)
*/
#include <iostream>
#include <cstdio>
#include <cstring>
#include <string>
#include <queue>
#define maxn 100
using namespace std;
char map[maxn][maxn];
struct point
{
int x;
int y;
//point(int a, int b){ x = a, y = b; }
//point(){};
}st,ed;
point DPlayer[22]; //防守员
int step[maxn][maxn]; //移动步数
int N,M,PlayerNum; //PlayerNum 防守员身体占的位置集合的个数
int LposX,LposY; //左上角坐标
int xx[] = {0,0,1,-1};
int yy[] = {1,-1,0,0};
int check(int x, int y) //判断是否可以移动。
{
if(step[x][y] != -1) return 0;
for(int i = 0; i < PlayerNum; i++)
{
int r = x - LposX + DPlayer[i].x; //左上角点横坐标改变的位置 + 原坐标 = 现坐标
int c = y - LposY + DPlayer[i].y; //。。。。纵。。。。。
if(r<0 || r>N-1 || c<0 || c>M-1) return 0; //超过边界
if(map[r][c] == 'O') return 0; //遇到 守卫
}
for(int i = 0; i < PlayerNum; i++)
{
int r = x - LposX + DPlayer[i].x; //左上角点横坐标改变的位置 + 原坐标 = 现坐标
int c = y - LposY + DPlayer[i].y; //。。。。纵。。。。。
if(map[r][c] == 'Q') return 2; //抓到 四分卫
}
return 1; //可以移动
}
int BFS(int stx, int sty)
{
if(LposX == -1) return -1;
memset(step,-1,sizeof(step));
queue <point> q;
st.x = stx; st.y = sty;
q.push(st);
step[stx][sty] = 0;
while(!q.empty())
{
st = q.front();
q.pop();
for(int i = 0; i < 4; i++)
{
ed.x = st.x + xx[i];
ed.y = st.y + yy[i];
int p = check(ed.x, ed.y);
if(p==0) continue;
if(p==2) return step[st.x][st.y]+1;
//移动 入队 步数加1
q.push(ed);
step[ed.x][ed.y] = step[st.x][st.y] + 1;
}
}
return -1;
}
int main(int argc, char *argv[])
{
while(scanf("%d%d",&N,&M) && (N||M))
{
getchar();
for(int i = 0; i < N; i++)
gets(map[i]);
LposX = -1, LposY = -1;
PlayerNum = 0;
for(int i = 0; i < N; i++)
{
for(int j = 0; j < M; j++)
{
if(map[i][j] == 'D')
{
DPlayer[PlayerNum].x = i;
DPlayer[PlayerNum++].y = j;
if(LposX == -1)
{
LposX = i;
LposY = j;
}
}
}
}
int ans = BFS(LposX,LposY);
if(ans == -1)
puts("Impossible");
else
printf("%d\n",ans);
}
return 0;
}