题目:
Description
给定M*N的矩阵,其中的每个元素都是-10到10之间的整数。你的任务是从左上角(1,1)走到右下角(M,N),每一步只能向右或向下,并且不能走出矩阵的范围。你所经过的方格里面的数字都必须被选取,请找出一条最合适的道路,使得在路上被选取的数字之和是尽可能小的正整数。
Input
第一行两个整数M,N,(2<=M,N<=10),分别表示矩阵的行和列的数目。 接下来的M行,每行包括N个整数,就是矩阵中的每一行的N个元素。
Output
仅一行一个整数,表示所选道路上数字之和所能达到的最小的正整数。如果不能达到任何正整数就输出-1。
Sample Input
2 2 0 2 1 0
Sample Output
1
方法一:记忆化搜索。
代码:
var i,j,n,m,ans:longint; f:array[0..11,0..11,-1001..1001] of boolean; a:array[0..11,0..11] of longint;PRocedure try(x,y,z:longint);begin f[x,y,z]:=true; if f[1,1,0] then exit; if (x-1>0) and not f[x-1,y,z-a[x-1,y]] then try(x-1,y,z-a[x-1,y]); if (y-1>0) and not f[x,y-1,z-a[x,y-1]] then try(x,y-1,z-a[x,y-1]);end;begin ans:=-1; read(n,m); for i:=1 to n do for j:=1 to m do read(a[i,j]); for i:=1 to n*m*10 do begin try(n,m,i-a[n,m]); if f[1,1,0] then begin ans:=i; break; end; end; write(ans);end.方法二:dp。
代码:
var m,n,i,j,k,ans:longint; a:array[0..11,0..11]of longint; f:array[0..11,0..11,-2000..2000]of boolean;begin fillchar(f,sizeof(f),false); readln(n,m); for i:=1 to n do for j:=1 to m do read(a[i,j]); f[1,1,a[1,1]]:=true; for j:=2 to m do for k:=-1000 to 1000 do if f[1,j-1,k] then f[1,j,k+a[1,j]]:=true; for i:=2 to n do for k:=-1000 to 1000 do if f[i-1,1,k] then f[i,1,k+a[i,1]]:=true; for i:=2 to n do for j:=2 to m do begin for k:=-1000 to 1000 do if f[i,j-1,k] then f[i,j,k+a[i,j]]:=true; for k:=-1000 to 1000 do if f[i-1,j,k] then f[i,j,k+a[i,j]]:=true; end; ans:=1; while (f[n,m,ans]=false)and(ans<=1000) do inc(ans); if ans=1001 then write(-1) else write(ans);end.方法总结:把走过的点记录下来。
新闻热点
疑难解答