打印矩阵中的所有路径

时间:2014-07-07 15:11:32

标签: c++ string recursion matrix

我正在尝试打印(nXm)中允许向右和向下移动的所有可能路径

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;
}

字符串ig如何被破坏。

例如: N = 3,M = 3

路径结束:(1,1),(2,1),(3,1),(3,2),(3,3),

路径结束: 1 ,1),(2,1),(2,2),(3,2),(3,3),

路径结束: 2 ,1),(2,1),(2,2),(2,3),(3,3),

路径结束: 1 ,1),(1,2),(2,2),(3,2),(3,3),

路径结束: 2 ,1),(1,2),(2,2),(2,3),(3,3),

路径结束: 2 ,1),(1,2),(1,3),(2,3),(3,3),

只有前两个字符,不知何故,被一个计数替换,其余的字符串是好的

我可以使用整数数组来打印它。但我不知道字符串变化的方式和原因?

2 个答案:

答案 0 :(得分:0)

str += p;pchar*时,最终会调用错误的重载 - 它会假定ppointer to the first element in a null-terminated array。将其更改为

str += (*p);

答案 1 :(得分:0)

正如chux指出的那样,你使用了未初始化的值p, 我建议使用std::to_string(C ++ 11)代替(非标准)itoa,如下所示: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;
    }
}