Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/162.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Matrix 打印矩阵中的所有路径_Matrix_C++_String_Recursion - Fatal编程技术网

Matrix 打印矩阵中的所有路径

Matrix 打印矩阵中的所有路径,matrix,c++,string,recursion,Matrix,C++,String,Recursion,我正在尝试打印(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,1

我正在尝试打印(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;
}
intn,m;
int findWays(int x,int y,string str)
{
int右下;
char*p;

如果(x
str+=p;
p
char*
时调用了错误的重载-它假设
p
是a。将其更改为

str += (*p);

正如chux所指出的,您使用未初始化的值
p
, 我建议使用
std::to_string
(C++11)代替(非标准)
itoa
,如下所示:

intfindways(intx,inty,std::string str)
{

如果(x
char*p;itoa(x,p,10);
,则没有空间放置
p
。请尝试
char p[50];
而不是(非标准)
itoa
,使用
std::to_string
(C++11)。谢谢,但是你知道为什么字符串被破坏了吗?p是未初始化的,可能会破坏内存。为什么在破坏中会有一个模式,无论我运行代码多少次都会破坏相同的输出。如果损坏的字符串给出随机输出,我会用未初始化的p解决,但我认为还有其他一些问题。
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;
    }
}