问题 -
给定一个大小为 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] +
off 移动到bottom
和right
的计算之外,并将其添加到return
计算中,那么它们就是等价的。你的第一个代码会导致有符号整数溢出,从而引发 UB。在至少一种情况下,你的第一个代码会触发INT_MAX
返回,然后将其添加到arr[start_x][start_y]
中并存储在bottom
(或right
)中。这个加法触发了溢出,因为int
不能比INT_MAX
更大。 - WhozCraig