# 代码

#include <iostream>
#include <cstdio>
#include <cmath>
#include <algorithm>
#include <cstring>
#include <stack>
#include <queue>
#include <string>
#include <vector>
#include <set>
#include <map>
#define fi first
#define se second
using namespace std;
typedef long long LL;
typedef pair<int,int> PII;
const int N = 15;
const int N2 = N * N;
const int M = N*N2*4 + N*N;
const int INF = 0x3f3f3f3f;

int dx[4] = {0, 0, 1, -1};
int dy[4] = {1, -1, 0, 0};

char s[N][N];
int dis[N2][4*N];
vector<PII> d;
vector<PII> p;

void bfs(int x, int n, int m) {
PII st = p[x];
int g[N][N];
memset(g, INF, sizeof g);
queue<PII> q;
q.push(st);
g[st.fi][st.se] = 0;
while (!q.empty()) {
PII cur = q.front();
q.pop();
for (int dir = 0; dir < 4; dir++) {
int cx = cur.fi + dx[dir], cy = cur.se + dy[dir];
if (g[cx][cy] != INF || cx < 0 || cx == n || cy < 0 || cy == m || s[cx][cy] == 'X') continue;
g[cx][cy] = g[cur.fi][cur.se] + 1;
if (s[cx][cy] == 'D') continue;
q.push(make_pair(cx, cy));
}
}

for (int i = 0; i < d.size(); i++) {
int cx = d[i].fi, cy = d[i].se;
dis[x][i] = g[cx][cy];
}
}

void init(int n, int m) {
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (s[i][j] == 'D') {
d.push_back(make_pair(i, j));
} else if (s[i][j] == '.') {
p.push_back(make_pair(i, j));
}
}
}
memset(dis, INF, sizeof dis);
for (int i = 0; i < p.size(); i++) {
bfs(i, n, m);
}
}

struct Edge {
int to, nxt;
Edge(int to, int nxt) : to(to), nxt(nxt) {}
Edge() {}
};
Edge e[N2*N2*N*8];
void addEdge(int from, int to, int cnt) {
}
void init(int n) {
for (int i = 0; i <= n; i++) head[i] = -1;
}

int match[M];
bool vis[M];

bool dfs(int x) {
vis[x] = true;
for (int i = head[x]; ~i; i = e[i].nxt) {
int to = e[i].to, w = match[to];
if (w == -1 || (!vis[w] && dfs(w))) {
match[x] = to;
match[to] = x;
return true;
}
}
return false;
}

bool solve(int n, int m) {
int ec = 0, mx = n*m, off = mx * d.size();
init(off + p.size());
for (int i = 0; i < p.size(); i++) {
for (int j = 0; j < d.size(); j++) {
for (int k = dis[i][j]; k <= mx; k++) {
int from = (k-1) * d.size() + j, to = off + i;
}
}
}

if (p.size() == 0) {
puts("0");
return true;
} else {
memset(match, -1, sizeof match);
int ans = 0;
for (int i = 0; i < off; i++) {
if (match[i] != -1) continue;
memset(vis, 0, sizeof vis);
if (dfs(i)) {
if (++ans == p.size()) {
printf("%d\n", i / d.size() + 1);
return true;
}
}
}
}
return false;
}

int main() {
int t, n, m;
scanf("%d", &t);
while (t--) {
scanf("%d%d", &n, &m);
for (int i = 0; i < n; i++) {
scanf("%s", s[i]);
}
init(n, m);
if (!solve(n, m)) {
puts("impossible");
}
d.clear();
p.clear();
}
return 0;
}
10-15 353
07-27 1716

02-18 134
05-08 47
08-19 804
08-29 137
08-14 959