取数字问题-SSL 1644

Description

  给定M*N的矩阵,其中的每个元素都是-1010之间的整数。你的任务是从左上角(11)走到右下角(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.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值