计数/打印路径 - 从(1,1)到(m,n)

时间:2014-11-25 00:48:23

标签: c++ recursion matrix path-finding

我想计算并打印从矩阵左下角到参数中给出的目的地的所有可能路径。您始终从坐标(1,1)开始,并且必须向上或向右移动。但是,目标是通过参数传递的。例如:CountPath(3,4)

我已经实现了正确查找路径数量,但发现我必须从我的目标开始并转到START,因为输入是目标位置。

int CountPath ( int row, int column )
{
   if ( row == 1 || column == 1 )
      return 1;
   else
      return CountPath(row - 1, column) + CountPath(row, column - 1);
}

输入/输出示例: 输入:3 4 输出:路径数为10

void main()
{
   int m, n;
   cin >> m >> n;
   cout << "The # of paths is " << CountPath( m, n ) << endl;
}

我需要澄清一下我是否正确地做了这个,或者是否有办法实际从(1,1)开始并向上和向右移动。打印应显示所有可能的路径,例如:

(1,1)-->(2,1)-->(3,1)-->(3,2)-->(3,3)-->(3,4)
(1,1)-->(2,1)-->(2,2)-->(3,2)-->(3,3)-->(3,4)
...

那么,是否有任何递归方式我可以从(1,1)开始并根据这些规则向上和向右移动?如果没有,我怎么能按照上面的顺序打印呢?

1 个答案:

答案 0 :(得分:0)

原因是您实现CountPath功能的方式。在if语句内部检查起始坐标,因为它们是最终的,在递归调用中,您递减坐标而不是递增它们。这应该按照您期望的方式运作:

int CountPath ( int row, int column, int maxRow, int maxColumn)
{
   if ( row == maxRow || column == maxColumn )
      return 1;
   else
      return CountPath(row + 1, column, maxRow, maxColumn) + CountPath(row, column + 1, maxRow, maxColumn);
}

现在你实际使用它的方式,也修改了一点点:

void main()
{
   int m, n;
   cin >> m >> n;
   cout << "The # of paths is " << CountPath( 1, 1, m, n ) << endl;
}