Sir, these days i am improving my recursion skills but i am stuck in one of the recursion problem of "Cracking the coding skills" book.
Problem number 8.2
Problem statement is -- Imagine a robot sitting on the upper hand corner of an N*N grid. The robot can only move in two directions: right and down. How many possible patha are there for the robot ?
I tried a lot but it only shows me a single path. My code is (taking help from solution of book)
#include<iostream>
#include<vector>
using namespace std;
struct point {
int x;
int y;
};
vector<struct point *> v_point;
int findPath(int x, int y) {
struct point *p = new point;
p->x = x;
p->y = y;
v_point.push_back(p);
if(x == 0 && y == 0) {
cout << "\n\t" << x << " " << y;
return true;
}
int success = 0;
if( x >= 1 ) {
cout << "\n success = " << success << " x = " << x << " " << " y = " << y;
success = findPath(x-1, y);
cout << "\n success = " << success << " x = " << x << " " << " y = " << y;
}
if(!success && y >= 1) {
cout << "\n\t success = " << success << " x = " << x << " " << " y = " << y;
success = findPath(x, y-1);
cout << "\n\t success = " << success << " x = " << x << " " << " y = " << y;
}
if(!success){
cout << "\n\t\t success = " << success << " x = " << x << " " << " y = " << y;
v_point.pop_back();
cout << "\n\t\t success = " << success << " x = " << x << " " << " y = " << y;
}
return success;
}
main() {
cout << endl << findPath(3, 3);
return 0;
}
I put printf statement to check where i am wrong, but i didn't find mistake. Please help me.
I wrote the code given by your instructions. But , if I want to print all the paths, it gives undesired answer.
int findPath(int x, int y) {
if(x == 0 && y == 0) { cout << endl; return 1; }
int path = 0;
if(x > 0) { cout << "d -> ";path = path + findPath(x-1, y); } // d = down
if(y > 0) { cout << "r -> ";path = path + findPath(x, y-1); } // r = right
return path;
}
for grid of 3*3 It gives ( findPaths(2, 2) ) :-
d -> d ->r -> r ->
r -> d -> r ->
r -> d->
r -> d -> d -> r ->
r -> d ->
r -> d -> d ->