首先bfs, 求出两两之间的距离, 然后dfs就可以。
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <cmath>
#include <string>
#include <queue>
#include <vector>
#include <map>
#include <set>
using namespace std;
#define pb(x) push_back(x)
#define ll long long
#define mk(x, y) make_pair(x, y)
#define mem(a) memset(a, 0, sizeof(a))
#define lson l, m, rt<<1
#define rson m+1, r, rt<<1|1
#define mem1(a) memset(a, -1, sizeof(a))
#define mem2(a) memset(a, 0x3f, sizeof(a))
#define rep(i, a, n) for(int i = a; i<n; i++)
#define ull unsigned long long
typedef pair<int, int> pll;
const double PI = acos(-1.0);
const int inf = ;
const double eps = 1e-;
const int mod = 1e9+;
const int dir[][] = { {-, }, {, }, {, -}, {, } };
char c[][];
int dis[][], vis[][], n, m, cnt, ans, used[];
struct node
{
int x, y, step;
node(){}
node(int x, int y, int step):x(x), y(y), step(step){}
};
int bfs(pll s, pll e) {
mem(vis);
vis[s.first][s.second] = ;
queue <node> q;
q.push(node(s.first, s.second, ));
while(!q.empty()) {
node tmp = q.front(); q.pop();
if(tmp.x == e.first && tmp.y == e.second)
return tmp.step;
for(int i = ; i<; i++) {
int tmpx = tmp.x + dir[i][];
int tmpy = tmp.y + dir[i][];
if(tmpx>=&&tmpx<n&&tmpy>=&&tmpy<m&&!vis[tmpx][tmpy]&&c[tmpx][tmpy]!='x') {
q.push(node(tmpx, tmpy, tmp.step+));
vis[tmpx][tmpy] = ;
}
}
}
return ;
}
void dfs(int now, int num, int now_dis) {
if(now_dis>=ans)
return ;
if(num == cnt-) {
if(now_dis<ans) {
ans = now_dis;
}
return ;
}
for(int i = ; i<cnt; i++) {
if(!used[i]) {
used[i] = ;
dfs(i, num+, now_dis+dis[now][i]);
used[i] = ;
}
}
}
pll point[];
int main()
{
while(scanf("%d%d", &m, &n)) {
if(n+m==)
break;
int sx, sy;
mem(dis);
cnt = ;
for(int i = ; i<n; i++)
scanf("%s", c[i]);
for(int i = ; i<n; i++) {
for(int j = ; j<m; j++) {
if(c[i][j] == 'o') {
c[i][j] = '';
point[].first = i;
point[].second = j;
}
if(c[i][j] == '*') {
point[cnt].first = i;
point[cnt++].second = j;
}
}
}
for(int i = ; i<cnt; i++) {
for(int j = i+; j<cnt; j++) {
dis[i][j] = dis[j][i] = bfs(point[i], point[j]);
}
}
int flag = ;
for(int i = ; i<cnt; i++) {
if(dis[][i] == ) {
flag = ;
}
}
if(flag) {
puts("-1");
continue;
}
mem(used);
used[] = ;
ans = inf;
dfs(, , );
printf("%d\n", ans);
}
}