Description
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?
Input
For each test case, there are two integers n and m.$(1 \leq n, m \leq 50)$.
The next n line, each line contains m integer. The j-th number of $i_{th}$ line a[i][j] means there are a[i][j] stones on the $j_{th}$ cell of the $i_{th}$ line.( $0 \leq a[i][j] \leq 100$ , and no more than 10 of a[i][j] will be positive integer).
Output
Sample Input
Sample Output
#include <iostream>
#include <stdio.h>
#include <string>
#include <string.h>
#include <algorithm>
#include <cmath>
using namespace std;
const int INF=99999999;
const int maxn=1<<10;
int n,m;
int dis[15][15],ct;
int dp[maxn+10][14];
struct node
{
int x,y;
}st[16];
void solve()
{
int tot=1<<ct;
for(int i=0;i<=maxn;i++)
for(int j=0;j<12;j++)
dp[i][j]=INF;
for(int i=0;i<ct;i++)
{
dp[1<<i][i]=abs(st[i].x-1)+abs(st[i].y-1);
// cout<<dp[1<<i][i]<<endl;
}
for(int i=1;i<tot;i++) //枚舉狀態集合
{
for(int j=0;j<ct;j++) //枚舉位置
{
if((i&(1<<j))==0)continue;
for(int k=0;k<ct;k++) //狀態轉移
{
if((i&(1<<k))==0)
{
dp[i|(1<<k)][k]=min(dp[i|(1<<k)][k],dp[i][j]+dis[j][k]);
}
}
}
}
int ans=INF;
for(int i=0;i<ct;i++)
{
ans=min(ans,dp[tot-1][i]+abs(st[i].x-1)+abs(st[i].y-1));
}
cout<<ans<<endl;
}
int main()
{
while( cin>>n>>m )
{
ct=0;
for(int i=1;i<=n;i++)
for(int j=1;j<=m;j++)
{
int tmp;
scanf("%d",&tmp);
if(tmp==0)continue;
if( i==1&&j==1 )continue;
st[ct].x=i;
st[ct++].y=j;
}
if(ct==0)
{
cout<<0<<endl;
continue;
}
for(int i=0;i<ct;i++)
for(int j=i+1;j<ct;j++)
{
dis[i][j]=abs(st[i].x-st[j].x)+abs(st[i].y-st[j].y);
dis[j][i]=dis[i][j];
}
solve();
}
return 0;
}