题目链接:http://poj.org/problem?id=2688
题意:一个机器人从'o'出发,要到达所有的'*',问最少的步数。
思路:1:状压dp可以做:2:求出每两个目标点的最短距离,然后dfs搜索最小答案。
#include<iostream>
#include<cstdio>
#include<cstring>
#include<string>
#include<algorithm>
#include<cmath>
#include<queue>
#define maxn 25
#define inf 1000000
using namespace std;
int n, m, start, sx, sy, num, ans;
char Map[maxn][maxn];
int x[] = {1, 0, -1, 0};
int y[] = {0, 1, 0, -1};
int dis[maxn][maxn];
bool vis[maxn][maxn];
bool use[maxn];
struct P
{
int step;
int x;
int y;
};
P node[maxn * maxn];
bool C(int x, int y)
{
if(x < 0 || x >= n || y < 0 || y >= m || Map[x][y] == 'x' || vis[x][y])
return 0;
return 1;
}
int BFS(P s, P e)
{
memset(vis, 0, sizeof(vis));
s.step = 0;
queue<P> Q;
Q.push(s);
while(!Q.empty())
{
P pre = Q.front(); Q.pop();
if(pre.x == e.x && pre.y == e.y)
{
return pre.step;
}
for(int i = 0; i < 4; i++)
{
int xx = pre.x + x[i];
int yy = pre.y + y[i];
if(C(xx, yy) && !vis[xx][yy])
{
vis[xx][yy] = 1;
P tmp;
tmp.x = xx;
tmp.y = yy;
tmp.step = pre.step + 1;
Q.push(tmp);
}
}
}
return inf;
}
void DFS(int s, int n, int Ans)
{
if(Ans > ans || n < 0)
{
return ;
}
if(!n && Ans < ans)
{
ans = Ans;
return ;
}
for(int i = 0; i < num; i++)
{
if(!use[i])
{
use[i] = 1;
DFS(i, n - 1, Ans + dis[s][i]);
use[i] = 0;
}
}
return ;
}
void pre()
{
num = 0;
for(int i = 0; i < maxn; i++)
{
for(int j = 0; j < maxn; j++)
{
dis[i][j] = inf;
}
}
}
int main()
{
while(scanf("%d %d", &m, &n))
{
if(!n && !m)
break;
pre();
for(int i = 0; i < n; i++)
{
scanf("%s", Map[i]);
for(int j = 0; j < m; j ++)
{
if(Map[i][j] == 'o' || Map[i][j] == '*')
{
node[num].x = i;
node[num].y = j;
if(Map[i][j] == 'o')
{
start = num;
}
num++;
}
}
}
bool flag = 1;
for(int i = 0; i < num; i++)
{
for(int j = i + 1; j < num; j++)
{
dis[i][j] = dis[j][i] = BFS(node[i], node[j]);
if(dis[i][j] == inf)
{
flag = 0;
break;
}
}
if(!flag)
break;
}
if(!flag)
{
cout << -1 << endl;
}
else
{
ans = inf;
memset(use, 0, sizeof(use));
use[start] = 1;
DFS(start, num - 1, 0);
printf("%d\n", ans);
}
}
return 0;
}