递归找到最便宜的可能路径

时间:2017-03-23 14:04:53

标签: c++ recursion path-finding

我正在尝试编写一个解决方案,通过一个数组找到最便宜的可能路径,并将整数值存储为游戏位置。这个想法是从第一个索引到最后一个索引,并根据您决定“停止”的索引产生最便宜的成本。你可以从你所在的位置移动到下一个索引,或者你可以跳过该索引到下一个索引(ind + 1 vs ind +2),直到你到达结尾。

我下面的内容是返回一个大的负整数,这显然是非常错误的。我相当肯定它与我如何控制当前位置有关,我不确定如何递归地执行它。这很容易迭代,但递归证明是困难的。 必须以递归方式完成有任何想法让我走上正确的道路吗?

#include "stdafx.h"
#include <iostream>
#include <array>

using namespace std;

const int GAMEBOARD_SIZE = 6;

int DetermineCheapestPath(int gameBoard[], int lowInd, int highInd, int currentLocation);

int main()
{
    int gameBoard[GAMEBOARD_SIZE] = { 0,3,80,6,57,10 };

    cout << "The cheapest possible path for this board is " << DetermineCheapestPath(gameBoard, 0, GAMEBOARD_SIZE - 1, 0) << endl;

    return 0;
}

int DetermineCheapestPath(int gameBoard[], int lowInd, int highInd, int currentLocation)
{
    int lastValue;
    int currentValue;
    //base case 
    if (lowInd == highInd)
    {
        currentLocation -= 1;
        return gameBoard[highInd];
    }
    else
    {
        lastValue = DetermineCheapestPath(gameBoard, lowInd + 1, highInd, currentLocation + 1);

        if (gameBoard[currentLocation] > gameBoard[currentLocation - 1] && currentLocation != 0 && lowInd != 0)
        {
            currentValue = gameBoard[currentLocation - 1];
            currentLocation -= 2;
            return lastValue + currentValue;
        }
        else if (gameBoard[currentLocation] < gameBoard[currentLocation - 1] && currentLocation != 0 && lowInd != 0)
        {
            currentValue = gameBoard[currentLocation];

            currentLocation -= 1;
            return lastValue + currentValue;
        }
        else
        {
            return lastValue + gameBoard[currentLocation];
        }
    }
}

0 个答案:

没有答案