【发布时间】:2019-12-15 13:20:25
【问题描述】:
问题-
给定一个由非负数填充的 m x n 矩阵,找到一条从左上角到右下角的路径,该路径最小化沿其路径的所有数字的总和。
注意:您只能在任何时间点向下或向右移动。
#include<iostream>
#include<climits>
using namespace std;
int min_cost(int arr[][2], int start_x, int start_y, int end_x, int end_y)
{
if(start_x > end_x || start_y > end_y)
return INT_MAX;
if( start_x == end_x && start_y == end_y)
return arr[end_x][end_y];
int bottom = arr[start_x][start_y] + min_cost(arr, start_x + 1, start_y, end_x, end_y); // Line 1
int right = arr[start_x][start_y] + min_cost( arr, start_x, start_y + 1, end_x, end_y); // Line 2
return min( bottom, right); // Line 3
}
int main()
{
int arr[2][2] = { {1,2},
{1,1},
};
cout <<"Min cost is " << min_cost(arr, 0, 0, 1, 1);
return 0;
}
输出
Min cost is -2147483647
预期输出
Min cost is 3
如果我使用下面的代码而不是主程序中的第 1、2 和 3 行,那么答案是正确的。
return arr[start_x][start_y] + min( min_cost(arr, start_x + 1, start_y, end_x, end_y),
min_cost( arr, start_x, start_y + 1, end_x, end_y));
为什么会这样?两个代码不一样吗? 任何帮助将不胜感激。
【问题讨论】:
-
它们不相等。如果您将
arr[start_x][start_y] +关闭bottom和right的计算,并将其添加到return计算中,然后 它们是等价的。您在调用 UB 的第一个代码中遇到有符号整数溢出。在至少一种情况下,您的第一个代码会触发INT_MAX返回,然后将其添加到arr[start_x][start_y]并存储在bottom(或right)中。该添加是触发溢出的原因,因为int不能大于INT_MAX。
标签: c++ algorithm dynamic-programming