先用BFS打出所有sheep----' # ' + ' D ' 的邻接矩阵.....arc[ i ] [ j ] 代表 i  到  j 的最短距离...我这里将 D 放在了 0  点...

      那么问题就转化为了有一个无向图  ...从确定的点出发( 0 ) 找一条路径...能遍历到其他所有点.并且在此前提下总长度最短...

      这个模型就是很经典的旅行商问题----哈密顿回路....但总所周知这个问题是NP难问题..没有较好的模型解决..这个题的点很少(16个'#'+1个 ‘D')...我首先得思路是枚举next_permutation..但16! 是很大的...不可行 ... 做DFS 的话也没有太好的条件来剪枝...各种超时..

       最终的方案还是 DP...可以考虑将问题切分为如此状态  dp [ k ] [ i ]  k代表当前有哪些点已经遍历了 ...i代表当前在哪个点上...由于每个点的遍历与否可以用0 or 1表示..所以k最大为2^16-1=65535....而i要注意...不是16而是17..因为还有起始的'D' 点...so..2^17*17..大约在10^7.. 可以接受...

       状态出来了...转移就so easy了....


Program:

#include<iostream>
#include<stdio.h>
#include<algorithm>
#include<string.h>
#include<math.h>
#include<map>
#include<queue>
#include<stack>
#define ll long long
#define oo 2000000000
#define pi acos(-1)
using namespace std;
struct node
{
int y,x,step;
}sheep[17],p,q;
int T,h,w,n,a[17],arc[17][17],ss[55][55],ans,k,dp[70000][20];
char s[55][55];
bool used[55][55];
queue<node> myqueue;
int main()
{
scanf("%d",&T);
while (T--)
{
scanf("%d%d",&h,&w);
int i,j;
n=0;
for (i=1;i<=h;i++)
{
scanf("%s",s[i]+1);
for (j=1;j<=w;j++)
if (s[i][j]=='#')
{
a[++n]=n;
ss[i][j]=n;
sheep[n].y=i;
sheep[n].x=j;
}else
if (s[i][j]=='U')
{
a[0]=0;
ss[i][j]=0;
sheep[0].y=i;
sheep[0].x=j;
}
}
memset(arc,-1,sizeof(arc));
for (i=0;i<=n;i++)
{
while (!myqueue.empty()) myqueue.pop();
p=sheep[i]; p.step=0;
myqueue.push(p);
memset(used,false,sizeof(used));
used[p.y][p.x]=true;
while (!myqueue.empty())
{
p=myqueue.front();
myqueue.pop();
if (s[p.y][p.x]=='#' || s[p.y][p.x]=='U')
{
k=ss[p.y][p.x];
arc[i][k]=p.step;
}
if (s[p.y][p.x]=='X') continue;
if (p.y-1>0 && !used[p.y-1][p.x])
{
q.y=p.y-1; q.x=p.x; q.step=p.step+1;
used[q.y][q.x]=true;
myqueue.push(q);
}
if (p.x-1>0 && !used[p.y][p.x-1])
{
q.y=p.y; q.x=p.x-1; q.step=p.step+1;
used[q.y][q.x]=true;
myqueue.push(q);
}
if (p.y+1<=h && !used[p.y+1][p.x])
{
q.y=p.y+1; q.x=p.x; q.step=p.step+1;
used[q.y][q.x]=true;
myqueue.push(q);
}
if (p.x+1<=w && !used[p.y][p.x+1])
{
q.y=p.y; q.x=p.x+1; q.step=p.step+1;
used[q.y][q.x]=true;
myqueue.push(q);
}
}
}
//-------------
int goal=1,x;
for (i=1;i<=n;i++) goal*=2;
goal--;
memset(dp,-1,sizeof(dp));
dp[0][0]=0;
for (k=1;k<=goal;k++)
{
h=k;
x=1;
i=0;
while (h)
{
i++;
if (h%2)
{
w=k-x;
for (j=0;j<=n;j++)
if (dp[w][j]!=-1 && arc[j][i]!=-1 &&
(dp[k][i]==-1 || dp[k][i]>dp[w][j]+arc[j][i]))
dp[k][i]=dp[w][j]+arc[j][i];
}
x*=2;
h/=2;
}
}
//-------------
ans=oo;
for (i=0;i<=n;i++)
if (dp[goal][i]!=-1 && dp[goal][i]<ans) ans=dp[goal][i];
if (ans==oo) printf("impossible\n");
else printf("%d\n",ans+n);
}
return 0;
}