Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 852 Accepted Submission(s): 348
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 <iostream> #include <stdio.h> #include <math.h> #include <stdlib.h> #include <algorithm> #include <string.h> using namespace std; const int INF = 999999999; struct Point { int x,y; } p[15]; int n,m,res,cnt; int graph[15][15]; bool vis[15]; void dfs(int x,int dept,int ans) { vis[x] = true; if(ans>res) return ; ///剪枝 if(dept==cnt-1) { ans += graph[x][0]; ///走回去 res = min(res,ans); return ; } for(int i=0; i<cnt; i++) { if(!vis[i]&&graph[x][i]!=INF&&x!=i) { dfs(i,dept+1,ans+graph[x][i]); vis[i] = false; } } } int main() { while(scanf("%d%d",&n,&m)!=EOF) { cnt = 0; int v; for(int i=0; i<n; i++) { for(int j=0; j<m; j++) { scanf("%d",&v); if(i==0&&j==0) { p[cnt].x = i,p[cnt++].y=j; } else if(v) { p[cnt].x = i,p[cnt++].y=j; } } } for(int i=0; i<cnt; i++) { for(int j=0; j<cnt; j++) { if(i==j)graph[i][j] = 0; else graph[i][j] =INF; } } for(int i=0; i<cnt; i++) { for(int j=i+1; j<cnt; j++) { graph[i][j] = graph[j][i] = abs(p[i].x-p[j].x)+abs(p[i].y-p[j].y); } } /*for(int i=0; i<cnt; i++) { for(int j=0; j<cnt; j++) { printf("%d ",graph[i][j]); } printf("\n"); }*/ memset(vis,false,sizeof(vis)); res = INF; vis[0] = true; dfs(0,0,0); printf("%d\n",res); } return 0; }