题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=4856
题解:……
类似的DP:http://blog.csdn.net/dolfamingo/article/details/71817743
代码如下:
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <string>
#include <vector>
#include <map>
#include <set>
#include <queue>
#include <sstream>
#include <algorithm>
using namespace std;
#define pb push_back
#define mp make_pair
#define ms(a, b) memset((a), (b), sizeof(a))
typedef long long LL;
const double eps = 1e-6;
const int INF = 2e9;
const LL LNF = 9e18;
const int mod = 1e9+7;
const int maxn = 20;
struct tunnel
{
int x1, y1, x2, y2;
}t[maxn];
struct node
{
int x, y, dis;
};
int n,m;
char maze[maxn][maxn];
int dis[maxn][maxn], dp[1<<15][maxn], vis[maxn][maxn];
int d[4][2] = {1,0,-1,0,0,1,0,-1};
int bfs(int st, int en)
{
queue<node>q;
while(!q.empty()) q.pop();
ms(vis,0);
vis[t[st].x2][t[st].y2] = 1;
node now, e;
now.x = t[st].x2; now.y = t[st].y2; now.dis = 0;
q.push(now);
while(!q.empty())
{
now = q.front();
q.pop();
if(now.x==t[en].x1 && now.y==t[en].y1)
return now.dis;
for(int i = 0; i<4; i++)
{
int x = now.x + d[i][0];
int y = now.y + d[i][1];
int dist = now.dis + 1;
if(x<1 || x>n || y<1 || y>n || maze[x][y]=='#' || vis[x][y]) continue;
vis[x][y] = 1;
e.x = x; e.y = y; e.dis = dist;
q.push(e);
}
}
return INF;
}
void solve()
{
for(int s = 0; s<(1<<m); s++)
for(int j = 0; j<m; j++)
dp[s][j] = INF;
for(int i = 0; i<m; i++)
dp[1<<i][i] = 0;
for(int s = 1; s<(1<<m); s++)
{
for(int j = 0; j<m; j++)
{
if(s&(1<<j) && dp[s][j]!=INF)
for(int k = 0; k<m; k++)
{
if( !(s&(1<<k)) && dis[k][j]!=INF)
{
int tmp = s|(1<<k);
dp[tmp][k] = min(dp[tmp][k],dp[s][j] + dis[k][j]);
}
}
}
}
int ans = INF;
for(int i = 0; i<m; i++)
ans = min(ans,dp[(1<<m)-1][i]);
if(ans!=INF)
printf("%d\n",ans);
else
puts("-1");
}
void build()
{
for(int i = 0; i<m; i++)
for(int j = 0; j<m; j++)
{
if(i==j)
dis[i][j] = 0;
else
dis[i][j] = bfs(i,j);
}
}
int main()
{
while(scanf("%d%d",&n,&m)!=EOF)
{
for(int i = 1; i<=n; i++)
scanf("%s",maze[i]+1);
for(int i = 0; i<m; i++)
scanf("%d%d%d%d",&t[i].x1, &t[i].y1, &t[i].x2, &t[i].y2);
build();
solve();
}
}