Matrix 打印矩阵中的所有路径
我正在尝试打印(nXm)中允许右下移动的所有可能路径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
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;
如果(xstr+=p;
当p
是char*
时调用了错误的重载-它假设p
是a。将其更改为
str += (*p);
正如chux所指出的,您使用未初始化的值p
,
我建议使用std::to_string
(C++11)代替(非标准)itoa
,如下所示:
intfindways(intx,inty,std::string str)
{
如果(xchar*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;
}
}