📌  相关文章
📜  在矩阵中最后一行的任何元素处结束的最大权重路径

📅  最后修改于: 2021-04-29 09:57:48             🧑  作者: Mango

给定一个整数矩阵,其中每个元素代表电池的重量。在矩阵[NXN]中找到权重最大的路径。路径遍历规则是:

  • 它应该从左上角的元素开始。
  • 路径可以在最后一行的任何元素处结束。
  • 我们可以从一个单元格(i,j)移至以下两个单元格。
    1. 下移:(i + 1,j)
    2. 对角移动:(i + 1,j + 1)

例子:

Input : N = 5
        mat[5][5] = {{ 4, 2 ,3 ,4 ,1 },
                     { 2 , 9 ,1 ,10 ,5 },
                     {15, 1 ,3 , 0 ,20 },
                     {16 ,92, 41, 44 ,1},
                     {8, 142, 6, 4, 8} };
Output : 255
Path with max weight : 4 + 2 +15 + 92 + 142 = 255                 

可以递归定义以上问题。

Let maxCost(i, j) be the cost maximum cost to
reach mat[i][j].  Since end point can be any point
in last row, we finally return maximum of all values
maxCost(N-1, j) where j varies from 0 to N-1.

If i == 0 and j == 0
   maxCost(0, 0) = mat[0][0]

// We can traverse through first column only by
// down move
Else if j = 0
  maxCost(i, 0) = maxCost(i-1, 0) + mat[i][0]

// In other cases, a cell mat[i][j] can be reached
// through previous two cells ma[i-1][j] and 
// mat[i-1][j-1]
Else
  maxCost(i, j) = mat[i][j] + max(maxCost(i-1, j),
                                maxCost(i-1, j-1)),

如果我们绘制上述递归解的递归树,则可以观察到重叠的子问题。由于该问题具有重叠的子问题,因此我们可以使用动态编程有效地解决它。以下是基于动态编程的解决方案。

C++
// C++ program to find the path having the
// maximum weight in matrix
#include
using namespace std;
const int MAX = 1000;
  
/* Function which return the maximum weight
   path sum */
int maxCost(int mat[][MAX], int N)
{
    // creat 2D matrix to store the sum of the path
    int dp[N][N];
    memset(dp, 0, sizeof(dp));
  
    dp[0][0] = mat[0][0];
  
    // Initialize first column of total weight
    // array (dp[i to N][0])
    for (int i=1; i


Java
// Java Code for Maximum weight path ending at 
// any element of last row in a matrix
import java.util.*;
  
class GFG {
      
    /* Function which return the maximum weight
       path sum */
    public static int maxCost(int mat[][], int N)
    {
        // create 2D matrix to store the sum of 
        // the path
        int dp[][]=new int[N][N];
          
        dp[0][0] = mat[0][0];
       
        // Initialize first column of total 
        // weight array (dp[i to N][0])
        for (int i = 1; i < N; i++)
            dp[i][0] = mat[i][0] + dp[i-1][0];
       
        // Calculate rest path sum of weight matrix
        for (int i = 1; i < N; i++)
           for (int j = 1; j < i + 1 && j < N; j++)
              dp[i][j] = mat[i][j] +
                        Math.max(dp[i-1][j-1], 
                                 dp[i-1][j]);
       
        // find the max weight path sum to reach
        // the last row
        int result = 0;
        for (int i = 0; i < N; i++)
            if (result < dp[N-1][i])
                result = dp[N-1][i];
       
        // return maximum weight path sum
        return result;
    }
      
    /* Driver program to test above function */
    public static void main(String[] args) 
    {
        int mat[][] = {  { 4, 1 ,5 ,6 , 1 },
                { 2 ,9 ,2 ,11 ,10 },
                { 15,1 ,3 ,15, 2 },
                { 16, 92, 41,4,3},
                { 8, 142, 6, 4, 8 }
            };
            int N = 5;
           System.out.println("Maximum Path Sum : "+ 
                               maxCost(mat, N));
    }
}
// This code is contributed by Arnav Kr. Mandal.


Python3
# Python3 program to find the path 
# having the maximum weight in matrix
  
MAX = 1000
  
# Function which return the 
# maximum weight path sum
def maxCost(mat, N):
      
    # creat 2D matrix to store the sum of the path
    dp = [[0 for i in range(N)] for j in range(N)]
  
    dp[0][0] = mat[0][0]
  
    # Initialize first column of total weight
    # array (dp[i to N][0])
    for i in range(1, N):
        dp[i][0] = mat[i][0] + dp[i - 1][0]
  
    # Calculate rest path sum of weight matrix
    for i in range(1, N):
        for j in range(1, min(i + 1, N)):
            dp[i][j] = mat[i][j] + \
                       max(dp[i - 1][j - 1],
                           dp[i - 1][j])
  
    # find the max weight path sum to reach
    # the last row
    result = 0
    for i in range(N):
        if (result < dp[N - 1][i]):
            result = dp[N - 1][i]
  
    # return maximum weight path sum
    return result
  
# Driver Program
  
mat = [ [4, 1 ,5 ,6 , 1],
        [2 ,9 ,2 ,11 ,10],
        [15,1 ,3 ,15, 2],
        [16, 92, 41,4,3],
        [8, 142, 6, 4, 8]]
  
N = 5
print('Maximum Path Sum :', maxCost(mat, N))
  
# This code is contributed by Soumen Ghosh.


C#
// C# Code for Maximum weight path
// ending at any element of last
// row in a matrix
using System;
  
class GFG {
      
    /* Function which return the
    maximum weight path sum */
    public static int maxCost(int [,] mat, int N)
    {
          
        // create 2D matrix to store the 
        // sum of the path
        int [,] dp = new int[N,N];
          
        dp[0,0] = mat[0,0];
      
        // Initialize first column of total 
        // weight array (dp[i to N][0])
        for (int i = 1; i < N; i++)
            dp[i,0] = mat[i,0] + dp[i-1,0];
      
        // Calculate rest path sum of weight matrix
        for (int i = 1; i < N; i++)
            for (int j = 1; j < i + 1 && j < N; j++)
                dp[i,j] = mat[i,j] +
                   Math.Max(dp[i-1,j-1], dp[i-1,j]);
      
        // find the max weight path sum to reach
        // the last row
        int result = 0;
          
        for (int i = 0; i < N; i++)
            if (result < dp[N-1,i])
                result = dp[N-1,i];
      
        // return maximum weight path sum
        return result;
    }
      
    /* Driver program to test above function */
    public static void Main() 
    {
        int [,] mat = { { 4, 1 ,5 ,6 , 1 },
                        { 2 ,9 ,2 ,11 ,10 },
                        { 15,1 ,3 ,15, 2 },
                        { 16, 92, 41,4,3},
                        { 8, 142, 6, 4, 8 }
                      };
        int N = 5;
          
        Console.Write("Maximum Path Sum : " 
                           + maxCost(mat, N));
    }
}
  
// This code is contributed by KRV.


PHP


输出:

Maximum Path Sum : 255

时间复杂度: O(N * N)