-1

I am attempting to find the minimum cost path of an array. The code works when restricted to moving either down or to the right, but not diagonally.

Issue:

return min(findMinCost( cost, m - 1, n), 
           findMinCost(cost, m, n - 1), 
           findMinCost(cost, m - 1, n - 1)) + cost[m - 1][n - 1];

I added the third argument for a diagonal movement, however it seems I cannot compare 3 arguments using min. What would be the easiest way to make this comparison? Thank you!

πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190
Kevinh56
  • 13
  • 2

1 Answers1

-1

In c++ min can take 2 arguments. You should calculate the min like this,

return min(
          min(findMinCost( cost, m - 1, n), 
              findMinCost(cost, m, n - 1)), 
              findMinCost(cost, m - 1, n - 1)) + cost[m - 1][n - 1];

That way, you will at first find the minimum between findMinCost( cost, m - 1, n) and findMinCost(cost, m, n - 1). And then find the minimum of the first minimum and findMinCost(cost, m - 1, n - 1). Its like if you want to find minimum of a,b,c,

int x = min(a, b);
int min = min(x, c);
πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190
Md Sabbir Alam
  • 4,937
  • 3
  • 15
  • 30
  • 2
    Actually, [min](https://en.cppreference.com/w/cpp/algorithm/min) can take a whole list of values and not just two. – Lukas-T Oct 21 '20 at 19:09
  • Yes, if we pass a list of values. But we can not pass more than 2 params for min function. I mean `min(integerList, compFunc)` is possible. But `min(a,b,c,d,...)` is not possible without overloading the min function. If I am missing something feel free to correct me. Thank you. – Md Sabbir Alam Oct 21 '20 at 19:14
  • @sabbir.alam [`std::min()`](https://en.cppreference.com/w/cpp/algorithm/min) (4) specifically. – πάντα ῥεῖ Oct 21 '20 at 19:18
  • Yes, but still you will be able to pass 2 parameters in the function. One of them is a list of numbers. But you can not pass more than 2 parameters, right? – Md Sabbir Alam Oct 21 '20 at 19:21
  • 2
    The first paramter can be an initializer list. So your above example can be written as `std::min({a, b, c, d})` - that's perfectly fine, the comparator is optional. – Lukas-T Oct 21 '20 at 19:26
  • Yes, i understand your answer. But {1,2,3,4} still count as one parameter to the min function. In the question above he is not passing a integer list. He is passing 3 different integer as prams. Which is not possible. – Md Sabbir Alam Oct 21 '20 at 19:31