0
votes

I am trying to print all the possible paths in a (nXm) where right and down movements are allowed

int n,m;

int findWays(int x, int y, string str)
{
    int right,down;
    char *p ;
    if(x<=n && y<=m)
    {
        str +="(";
        itoa(x,p,10);
        str += p;
        str += ",";
        itoa(y,p,10);
        str += p;
        str +="),";
     //   cout<< "X : "<<x<<" Y : "<<y<<endl<<str<<endl;
        if(x==n && y==m)
        {
            cout<<"Path End : "<<str<<endl;
            return 1;
        }
     //   cout<<"Going Right : "<<str<<endl;
        right = findWays(x+1,y,str);
        //cout<<"Going Down : "<<str<<endl;
        down = findWays(x,y+1,str);
        return (right+down);
    }
    else
    {
        return 0;
    }
}

int main()
{
    string str;
    int count;
    cout<< "Enter N and M: ";
    cin>>n>>m;
    cout<<"Paths :\n";
    count = findWays(1,1,str);
    cout<<" Total no of Paths : "<<count;
    return 0;
}

some how the string ig getting corrupted.

eg: n=3,m=3

Path End : (1,1),(2,1),(3,1),(3,2),(3,3),

Path End : 1 ,1),(2,1),(2,2),(3,2),(3,3),

Path End : 2 ,1),(2,1),(2,2),(2,3),(3,3),

Path End : 1 ,1),(1,2),(2,2),(3,2),(3,3),

Path End : 2 ,1),(1,2),(2,2),(2,3),(3,3),

Path End : 2 ,1),(1,2),(1,3),(2,3),(3,3),

only the first two character, somehow, replaced by a count and rest of the string is good

I can use a integer array instead and print it. But I don't know how and why the string getting changed?

2
char *p ; itoa(x,p,10);, no space for p. Try char p[50]; - chux - Reinstate Monica
Instead of (non-standard) itoa, use std::to_string (C++11). - Jarod42

2 Answers

0
votes

As point out by chux, you use an uninitialized value p, I suggest to use std::to_string (C++11) instead of (non standard) itoa as follow: https://ideone.com/h5hPj1

int findWays(int x, int y, std::string str)
{
    if (x <= n && y <= m)
    {
        str += "(";
        str += std::to_string(x);
        str += ", ";
        str += std::to_string(y);
        str +="), ";
        if (x == n && y == m)
        {
            std::cout << "Path End : " << str << std::endl;
            return 1;
        }
        int right = findWays(x + 1, y, str);
        int down = findWays(x, y + 1, str);
        return (right + down);
    }
    else
    {
        return 0;
    }
}
0
votes

str += p; when p is a char* ends up invoking the wrong overload - it assumes that p is a pointer to the first element in a null-terminated array. Change it to

str += (*p);