具有多个条件的2D整数矩阵中的最大路径总和-动态编程

时间:2018-09-06 19:27:00

标签: c++ dynamic-programming

在等腰三角形上有一个机器人:

2
12 15
10 14 19
-9 -30 12 8
-8 -50 1 14 9
99 150 11 10 9 7

它位于左上角。它可以通过两种方式一次移动一个步骤:右下或向下。矩阵可以包含正负元素。

找到最大路径总和的简单问题非常简单。对于此问题,以下重复关系成立:

cost[i][j] = mat[i][j] + max(cost[i-1][j-1], cost[i-1][j]);

实现如下。

还有两个附加条件:

  • 机器人可以随时停下来,他不必到达底线就可以得到最大的收益。
  • 您可以选择从最后获得的整个最大路径中删除一个点(只有一个),以使总和最大化。

如何修改解决方案以解决上述情况?

这是我目前编写的代码。

int maxPathSum(vector<vector<int>> mat, int n)
{
    vector<vector<int>> cost(n+2, vector<int>(n+2, 0));
    vector<vector<char>> pred(n+2, vector<char>(n+2, '$'));

    cost[1][1] = mat[1][1];
    pred[1][1] = 'S';
    for(int i=2; i<=n; i++)
    {
        cost[i][1] = cost[i-1][1] + mat[i][1];
        pred[i][1] = 'U';
    }



    for(int i=2; i<=n; i++) {
        for(int j=2; j<=n; j++) {
            if(i>=j) {
                cost[i][j] = mat[i][j] + max(cost[i-1][j-1],cost[i-1][j]);
                if(cost[i-1][j-1]>cost[i-1][j]) {
                    pred[i][j] = 'D';
                }
                else {
                    pred[i][j] = 'U';
                }
            }
        }
    }
    int maxSum = 0;
    int posi, posj;
    for(int i=1; i<=n; i++) {
        if(mat[n][i] > maxSum) {
            maxSum = cost[n][i];
            posi = n;
            posj = i;
        }
    }
    cout << "The max sum is " << maxSum << endl;

    pairs p;
    vector<pairs> result;

    while(pred[posi][posj] != '$')
    {

        p.a = posi;
        p.b = posj;
        result.push_back(p);
        if (pred[posi][posj] == 'D') {
            posi -= 1;
            posj -= 1;
        }
        else {
            posi -= 1;
        }
    }

    reverse(result.begin(),result.end());
    cout<<"A maximum path is "<<endl;
    for(auto it:result) {
        cout<<it.a<<" "<<it.b<<endl;
    }
}

0 个答案:

没有答案