【发布时间】:2014-08-28 03:11:11
【问题描述】:
我正在尝试在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),
只有前两个字符,不知何故,被替换为一个计数,其余的字符串是好的
我可以改用整数数组并打印它。但我不知道字符串是如何以及为什么被改变的?
【问题讨论】:
-
char *p ; itoa(x,p,10);,p没有空格。试试char p[50]; -
代替(非标准)
itoa,使用std::to_string(C++11)。
标签: matrix c++ string recursion matrix