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
题解:这题可以用深度化搜索,
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]);
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.
取数字问题-SSL 1644
最新推荐文章于 2023-12-31 20:23:42 发布