fork download
  1. /*Given grid of positive numbers, strat from (0,0) ad end at (n,n).
  2.   Move only to RIGHT and DOWN. Find path with sum of numbers is maximum. */
  3.  
  4. #include <algorithm>
  5. #include<iostream>
  6.  
  7. const int grid[2][3] = { { 5, 1, 2 }, { 6, 7, 8 } };
  8.  
  9. bool valid (int r, int c)
  10. {
  11. return r < 2 && c < 3;
  12. }
  13.  
  14. int maxPathSum (int row, int column)
  15. {
  16. if (!valid (row, column))
  17. return 0;
  18.  
  19. if (row == 1 && column == 2) //base condition
  20. return grid[row][column];
  21.  
  22. int path1 = maxPathSum (row, column + 1); //Right
  23. int path2 = maxPathSum (row + 1, column); //Down
  24.  
  25. return grid[row][column] + std::max(path1, path2);
  26. }
  27.  
  28. int main ()
  29. {
  30. std::cout << maxPathSum (0, 0) << std::endl;
  31. return 0;
  32. }
  33.  
Success #stdin #stdout 0s 3340KB
stdin
Standard input is empty
stdout
26