使用递归查找路径

时间:2016-06-02 15:38:23

标签: c++ recursion

这是问题

假设我们有一个nxn方板,里面的每个小方块都包含1或0.从左上角的方块(0,0)开始,找到右边最低方块(n,n)的路径产生从它通过的所有方格制成的最大的binery数。

**Input**
first line: n.  
the following n lines : each line contains n numbers of 0 or 1.  

**Output**
the decimal number of the largest binary string you found.

这是我的代码。我使用递归来查找移动到最后一个方格的所有路径,并且每条路径生成二进制字符串并将它们放入向量中。最后,我将在矢量中打印最大的数字。

#include <iostream>
#include <cmath>
#include <queue>
#include <string>
#include <algorithm>
using namespace std;
#define rep(I,N) for(int I=0;I<(N);++I)
int n;
char field[100][100];
vector<string>bin;
vector<int>de;
string tmp;

int dec(string bin)
{
    int d=0;
    for (int i = bin.size() - 1;i >= 0;--i)
        if (bin[i] == '1')d += pow(2, i);
    return d;
}

void path(int x = 0,int y = 0)
{

    if(x>n-1||y>n-1)
    return;
    else if(x==n-1&&y==n-1)
    {
        tmp.push_back(field[x][y]);
        reverse(tmp.begin(), tmp.end());
        de.push_back(dec(tmp));
        tmp.clear();
    }
    else
    {
        tmp.push_back(field[x][y]);
        path(x + 1, y);
        path(x, y + 1);
    }
}

int main()
{
    cin >> n;
    rep(i,n)rep(j,n)
        cin >> field[i][j];
    path();
    cout << *max_element(de.begin(), de.end());
    return 0;   
}  

我从老师那里得到的样本测试是

5 

-1 -0 -1  1  0    
0  0 -1  0  1  
0  0 -1  0  1  
1  0 -0 -1  1  
1  1  0 -1 -0  

哪个应该打印374这是101110010(我从测试中标记的路径)但是当我在我的代码上使用它时,它就像这条路径一样打印出来。

-1  0  1  1  0    
-0  0  1  0  1  
-0  0  1  0  1  
-1  0  0  1  1  
-1 -1 -0 -1 -0  

我试过调试,它似乎只能找到一些路径,但我无法确定确切的问题。有人可以告诉我我的代码有什么问题以及如何修复它,非常感谢你。

1 个答案:

答案 0 :(得分:0)

清除目标处的路径将阻止搜索从路径中间分支的路径。您应该使用pop_back来取回。

试试这个:

void path(int x = 0,int y = 0)
{

    if(x>n-1||y>n-1)
    return;
    else if(x==n-1&&y==n-1)
    {
        tmp.push_back(field[x][y]);
        reverse(tmp.begin(), tmp.end());
        de.push_back(dec(tmp));
        reverse(tmp.begin(), tmp.end());
        tmp.pop_back();
    }
    else
    {
        tmp.push_back(field[x][y]);
        path(x + 1, y);
        path(x, y + 1);
        tmp.pop_back();
    }
}

请注意,为了使返回后的路径正确,必须再次颠倒反转的内容。

相关问题