DP方法?输出应该是最大总和。在知名公司面试(仍然没有想法,任何提示)

时间:2018-06-11 21:22:56

标签: dynamic-programming

您有一张表,每个单元格中都有一个正整数或单元格被阻止。你有一个玩家从左下角开始,想要以这样一种方式到达右上角,这样你就可以最大化整数之和。您只能向上或向右移动,但不能通过阻塞的单元格。输出应该是最大值。

1 个答案:

答案 0 :(得分:0)

在我的代码中,我假设答案适合长长的类型。 我也假设这是一个方形矩阵,为简单起见,但你可以几乎不费力地调整任何矩形矩阵的算法。 如果输入矩阵是N×N,则该方法的复杂度为O(N ^ 2)。

#include <vector>
#include <iostream>
#include <algorithm>

constexpr int maxDimension = 100;

using namespace std;

long long matrix[maxDimension][maxDimension];
long long dp[maxDimension][maxDimension];

int main()
{
    // I am assuming that the matrix is filled with positive
    // integers, and the blocked cell's are filled with -1.

    // reading the values for the matrix
    for(int i = 0; i < maxDimension; ++i) 
    {
        for(int j = 0; j < maxDimension; ++j) 
        {
            cin >> matrix[i][j];
        }
    }

    /*
        For every pair(i, j), 
        dp[i][j] is the maximum 
        sum we can achive going from
        (0,0) to (i, j)
    */

    // Observation if dp[i][j] is equal to -1, it is because we cannot reach the cell (i, j) because of blocked cells
    dp[0][0] = matrix[0][0];


    // this calculates the dp for row == 0
    for(int col = 1; col < maxDimension; ++col)
    {
        if(dp[0][col - 1] != -1 && matrix[0][col] != -1) 
        {
            dp[0][col] = dp[0][col-1] + matrix[0][col];
        }
        else dp[0][col] = -1;
    }

    // now I will calculate the dp for column == 0
    for(int row = 1; row < maxDimension; ++row) 
    {
        if(dp[row - 1][0] != -1 && matrix[row][0] != -1)
        {
            dp[row][0] = dp[row-1][0] + matrix[row][0];
        }
        else dp[row][0] = -1;
    }

    // Now that I have calculated the base cases, I will calculate the dp for the other states
    // I will use the following expression 
    /* dp[i][j] =  if (matrix[i][j] == -1)                        -> -1
                   else if (dp[i-1][j] != -1 or dp[i][j-1] != -1) -> max(dp[i-1][j], dp[i][j - 1]) + matrix[i][j]
                   else                                           -> -1
    */
    for(int row = 1; row < maxDimension; ++row)
    {
        for(int col = 1; col < maxDimension; ++col)
        {
            if(matrix[i][j] != -1 && ( dp[i-1][j] != -1 || dp[i][j-1] != -1) )
            {
                dp[i][j] = max(dp[i-1][j], dp[i][j-1]) + matrix[i][j];
            }
            else dp[i][j] = -1;
        }
    }

    if(dp[maxDimension-1][maxDimension-1] == -1) cout << "The top right cell is not reachable from the bottom left cell" << endl;
    else cout << "The best sum possible is " << dp[maxDimension - 1][maxDimension - 1] << endl;

    return 0;
}
相关问题