Dumbledore, the headmaster of Hogwarts, is planning to construct a new teaching building in his school. The area he selects can be considered as an n*m grid, some (but no more than ten) cells of which might contain stones. We should remove the stones there in order to save place for the teaching building. However, the stones might be useful, so we just move them to the top-left cell. Taking it into account that Harry learned how to operate dig machine in Lanxiang School several years ago, Dumbledore decides to let him do this job and wants it done as quickly as possible. Harry needs one unit time to move his dig machine from one cell to the adjacent one. Yet skilled as he is, it takes no time for him to move stones into or out of the dig machine, which is big enough to carry infinite stones. Given Harry and his dig machine at the top-left cell in the beginning, if he wants to optimize his work, what is the minimal time Harry needs to finish it?
For each test case, there are two integers n and m.(1≤n,m≤50).
The next n line, each line contains m integer. The j-th number of ith line a[i][j] means there are a[i][j] stones on the jth cell of the ith line.( 0≤a[i][j]≤100 , and no more than 10 of a[i][j] will be positive integer).
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
using namespace std;
#define inf 9999999
int dp[(1<<11)+5][15];
int ma[15][15];
struct node
{
int x,y;
}e[15];
int main()
{
int n,m,xx;
while(scanf("%d%d",&n,&m)!=EOF)
{
int k=1;
e[0].x=0;
e[0].y=0;
for(int i=0;i<n;i++)
{
for(int j=0;j<m;j++)
{
scanf("%d",&xx);
if(i==0&&j==0)continue;
if(xx!=0)
{
e[k].x=i;
e[k].y=j;
k++;
}
}
}
for(int i=0;i<k;i++)
{
for(int j=0;j<k;j++)
{
if(i!=j)
ma[i][j]=inf;
}
}
for(int i=0;i<k;i++)
{
for(int j=0;j<k;j++)
{
if(i==j)continue;
if(ma[i][j]>(abs(e[i].x-e[j].x)+abs(e[i].y-e[j].y)))
{
ma[i][j]=ma[j][i]=abs(e[i].x-e[j].x)+abs(e[i].y-e[j].y);
}
}
}
for(int s=0;s<(1<<k);s++)
{
for(int j=0;j<k;j++)
{
dp[s][j]=inf;
}
}
for(int s=0;s<(1<<k);s++)
{
for(int now=0;now<k;now++)
{
if(!(s&(1<<now)))continue;
if((1<<now)==s)
{
dp[s][now]=ma[0][now];//當此轉貸s中只含一個點時,一定是從0點到詞此點
continue;
}
for(int i=0;i<k;i++)
{
if(i==now)continue;
if(!(s&(1<<i)))continue;
int snow=(1<<now)^s;
if(dp[snow][i]==inf)continue;
dp[s][now]=min(dp[snow][i]+ma[i][now],dp[s][now]);
}
}
}
int ans=inf;
for(int i=0;i<k;i++)
ans=min(dp[(1<<k)-1][i]+ma[0][i],ans);
if(ans!=inf)
printf("%d\n",ans);
else
printf("0\n");
}
return 0;
}