C++ Program to check k rupees are enough to reach final cell or not

C++Server Side ProgrammingProgramming

Suppose we have three numbers n, m and k. There is a n x m grid. we are currently at cell (0,0) top left corner and we want to reach cell (n - 1, m - 1). We can move to the neighboring cells to the right or down. To reach down, it will take x rupees, and to reach right cell, it will take y rupees. We have to check whether we can reach cell (n - 1, m - 1) spending exactly k rupees or not. (The x and y are the current x and y coordinate of the cell + 1)

Problem Category

The given problem is an example of a divide-and-conquer problem that we can solve using Dynamic programming. Dynamic programming is a type of divide-and-conquer technique where a particular problem is divided into subproblems and then solved. There is a difference between the normal divide-and-conquer technique and dynamic programming, that is the latter solves the overlapping subproblems and uses that result whenever it is needed again. To store the result of these overlapping subproblems, the dynamic programming technique uses a table, and this process is called 'memoization'. The data from the table is examined each time a subproblem has to be solved. Typically, dynamic programming techniques are used for optimization problems where an optimal value of a solution has to be found. Examples of this programming technique include Fibonacci series problems, Bellman-Ford single-source shortest path problem, matrix chain multiplication problem, longest common subsequence problem, etc.


So, if the input of our problem is like n = 2; m = 2; k = 3, then the output will be True.


To solve this, we will follow these steps −

if k is same as n * m - 1, then:
   return true
   return false


Let us see the following implementation to get better understanding −

#include <bits/stdc++.h>
using namespace std;
bool solve(int n, int m, int k){
   if (k == n * m - 1)
      return true;
      return false;
int main(){
   int n = 2;
   int m = 2;
   int k = 3;
   cout << solve(n, m, k) << endl;


2, 2, 3


Updated on 08-Apr-2022 08:15:00