【问题标题】:Finding path using recursion使用递归查找路径
【发布时间】:2016-06-02 15:38:23
【问题描述】:

问题来了

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

**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(我从测试中标记的路径),但是当我在代码中使用它时,它会像这条路径一样打印 314。

-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 &lt;&lt; i 而不是pow(2, i),因为我认为浮点算术可能包含错误。
  • 我写了一个有点类似的移动瓷砖拼图求解器here,这可能会有所帮助。

标签: c++ recursion


【解决方案1】:

清除目标处的路径将阻止搜索从路径中间分支的路径。您应该使用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();
    }
}

注意,为了使返回后的路径正确,必须再次反转它。

【讨论】:

    猜你喜欢
    • 2017-09-24
    • 1970-01-01
    • 2013-03-14
    • 2011-04-22
    • 2020-02-14
    • 1970-01-01
    • 1970-01-01
    • 2014-11-10
    • 2013-12-19
    相关资源
    最近更新 更多