📌  相关文章
📜  从给定矩阵的左上角到右下角的路径的最大非负乘积

📅  最后修改于: 2021-09-06 06:46:54             🧑  作者: Mango

给定一个维度为N * M的整数矩阵mat[][] ,任务是打印从左上角单元格(0, 0)到右下角单元格(N – 1 )路径中矩阵元素的最大乘积, M – 1)的给定矩阵。任何单元格(i, j) 的唯一可能移动是(i + 1, j)(i, j + 1) 。如果最大乘积为负,则打印“-1”

例子:

朴素方法:最简单的求解方法是从左上角单元格递归遍历,并通过从每个单元格向右和向下移动,生成从左上角到右下角单元格的所有可能路径。找到生成的每个路径的乘积并打印其中的最大值。
时间复杂度: O(2 max(N, M) )
辅助空间: O(1)

高效的方法:为了优化上述方法,思想是使用动态规划。请按照以下步骤解决问题:

  • 初始化矩阵maxPath[][]minPath[][] ,分别存储路径的最大和最小乘积。
  • 这个想法也是跟踪到目前为止获得的最大负积,因为如果遇到任何负积,那么负积乘以最大负积可以生成最大正积
  • 要达到索引(i, j),由于允许的可能移动是向右和向下,因此最大乘积可以是最大乘积或最小乘积,直到第(i – 1, j) 个索引或第(i, j – 1)索引乘以索引(i, j)处的元素。
  • 完成上述步骤后,如果maxPath[M – 1][N – 1]的值为非负,则将其打印为正乘积路径。否则,打印“-1”

下面是上述方法的实现:

C++
// C++ program for the above approach
#include 
 
using namespace std;
 
// Function to find the maximum product
// from the top left and bottom right
// cell of the given matrix grid[][]
int maxProductPath(vector> grid){
 
    // Store dimension of grid
    int n = grid.size();
    int m = grid[0].size();
 
    // Stores maximum product path
    vector> maxPath(n, vector(m, 0));
 
    // Stores minimum product path
    vector>  minPath(n, vector(m, 0));
 
    // Traverse the grid and update
    // maxPath and minPath array
    for (int i = 0; i < n; i++)
    {
        for (int j = 0; j < m; j++)
        {
 
            // Initialize to inf and -inf
            int mn = INT_MAX;
            int mx = INT_MIN;
 
            // Base Case
            if (i == 0 and j == 0)
            {
                mx = grid[i][j];
                mn = grid[i][j];
              }
 
            // Calculate for row:
            if (i > 0)
            {
                int tempmx = max((maxPath[i - 1][j] * grid[i][j]),
                             (minPath[i - 1][j] * grid[i][j]));
 
                // Update the maximum
                mx = max(mx, tempmx);
                int tempmn = min((maxPath[i - 1][j] * grid[i][j]),
                             (minPath[i - 1][j] * grid[i][j]));
 
                // Update the minimum
                mn = min(mn, tempmn);
              }
 
            // Calculate for column:
            if (j > 0)
            {
                int tempmx = max((maxPath[i][j - 1] * grid[i][j]),
                             (minPath[i][j - 1] * grid[i][j]));
 
                // Update the maximum
                mx = max(mx, tempmx);
                int tempmn = min((maxPath[i][j - 1] * grid[i][j]),
                             (minPath[i][j - 1] * grid[i][j]));
 
                // Update the minimum
                mn = min(mn, tempmn);
              }
 
            // Update maxPath and minPath
            maxPath[i][j] = mx;
            minPath[i][j] = mn;
          }
        }
   
    // If negative product
    if(maxPath[n - 1][m - 1] < 0)
        return -1;
    // Otherwise
    else
        return(maxPath[n - 1][m - 1]);
}
 
// Driver Code
int main(){
   
// Given matrix mat[][]
  vector> mat = {{1, -2, 1},
                            {1, -2, 1},
                            {3, -4, 1}};
  // Function Call
  cout<<(maxProductPath(mat));
 
}
 
// This code is contributed by mohit kumar 29


Java
// Java program for the above approach
import java.io.*;
class GFG
{
 
  // Function to find the maximum product
  // from the top left and bottom right
  // cell of the given matrix grid[][]
  static int maxProductPath(int[][] grid)
  {
 
    // Store dimension of grid
    int n = grid.length;
    int m = grid[0].length;
 
    // Stores maximum product path
    int[][] maxPath = new int[n][m];
 
    // Stores minimum product path
    int[][] minPath = new int[n][m];
 
    // Traverse the grid and update
    // maxPath and minPath array
    for(int i = 0; i < n; i++)
    {
      for (int j = 0; j < m; j++)
      {
        // Initialize to inf and -inf
        int mn = Integer.MAX_VALUE;
        int mx = Integer.MIN_VALUE;
 
        // Base Case
        if(i == 0 && j == 0)
        {
          mx = grid[i][j];
          mn = grid[i][j];
        }
 
        // Calculate for row:
        if(i > 0)
        {
          int tempmx =Math.max((maxPath[i - 1][j] *
                                grid[i][j]),(minPath[i - 1][j] *
                                             grid[i][j]));
 
          // Update the maximum
          mx = Math.max(mx, tempmx);
          int tempmn = Math.min((maxPath[i - 1][j] *
                                 grid[i][j]),(minPath[i - 1][j] *
                                              grid[i][j]));
 
          // Update the minimum
          mn=Math.min(mn, tempmn);            
        }
 
        // Calculate for column
        if(j > 0)
        {
          int tempmx = Math.max((maxPath[i][j - 1] *
                                 grid[i][j]),(minPath[i][j - 1] *
                                              grid[i][j]));
 
          // Update the maximum
          mx = Math.max(mx, tempmx);
          int tempmn = Math.min((maxPath[i][j - 1] *
                                 grid[i][j]),(minPath[i][j - 1] *
                                              grid[i][j]));
 
          // Update the minimum
          mn=Math.min(mn, tempmn);
        }
 
        // Update maxPath and minPath
        maxPath[i][j] = mx;
        minPath[i][j] = mn;
      }
    }
 
    // If negative product
    if(maxPath[n - 1][m - 1] < 0)
    {
      return -1;
    }
 
    // Otherwise
    else
    {
      return(maxPath[n - 1][m - 1]);
    }
  }
 
  // Driver Code
  public static void main (String[] args)
  {
 
    // Given matrix mat[][]
    int[][] mat = {{1, -2, 1}, {1, -2, 1}, {3, -4, 1}};
 
    // Function Call
    System.out.println(maxProductPath(mat));
  }
}
 
// This code is contributed by rag2127


Python3
# Python program for the above approach
 
# Function to find the maximum product
# from the top left and bottom right
# cell of the given matrix grid[][]
def maxProductPath(grid):
 
    # Store dimension of grid
    n, m = len(grid), len(grid[0])
 
    # Stores maximum product path
    maxPath = [[0 for i in range(m)] for j in range(n)]
 
    # Stores minimum product path
    minPath = [[0 for i in range(m)] for j in range(n)]
 
    # Traverse the grid and update
    # maxPath and minPath array
    for i in range(n):
        for j in range(m):
 
            # Initialize to inf and -inf
            mn = float("inf")
            mx = float("-inf")
 
            # Base Case
            if (i == 0 and j == 0):
                mx = grid[i][j]
                mn = grid[i][j]
 
            # Calculate for row:
            if i > 0:
                tempmx = max((maxPath[i - 1][j] * grid[i][j]),
                             (minPath[i - 1][j] * grid[i][j]))
 
                # Update the maximum
                mx = max(mx, tempmx)
                tempmn = min((maxPath[i - 1][j] * grid[i][j]),
                             (minPath[i - 1][j] * grid[i][j]))
 
                # Update the minimum
                mn = min(mn, tempmn)
 
            # Calculate for column:
            if (j > 0):
                tempmx = max((maxPath[i][j - 1] * grid[i][j]),
                             (minPath[i][j - 1] * grid[i][j]))
 
                # Update the maximum
                mx = max(mx, tempmx)
                tempmn = min((maxPath[i][j - 1] * grid[i][j]),
                             (minPath[i][j - 1] * grid[i][j]))
 
                # Update the minimum
                mn = min(mn, tempmn)
                 
            # Update maxPath and minPath
            maxPath[i][j] = mx
            minPath[i][j] = mn
 
    # If negative product
    if(maxPath[n - 1][m - 1] < 0):
        return -1
       
    # Otherwise
    else:
        return(maxPath[n - 1][m - 1])
 
# Driver Code
 
# Given matrix mat[][]
mat = [[1, -2, 1],
        [1, -2, 1],
        [3, -4, 1]]
 
# Function Call
print(maxProductPath(mat))


C#
// C# program for the above approach
using System;
class GFG
{
 
  // Function to find the maximum product
  // from the top left and bottom right
  // cell of the given matrix grid[][]
  static int maxProductPath(int[,] grid)
  {
 
    // Store dimension of grid
    int n = grid.GetLength(0);
    int m = grid.GetLength(1);
 
    // Stores maximum product path
    int[,] maxPath = new int[n, m];
 
    // Stores minimum product path
    int[,] minPath = new int[n, m];
 
    // Traverse the grid and update
    // maxPath and minPath array
    for(int i = 0; i < n; i++)
    {
      for (int j = 0; j < m; j++)
      {
 
        // Initialize to inf and -inf
        int mn = Int32.MaxValue;
        int mx = Int32.MinValue;
 
        // Base Case
        if(i == 0 && j == 0)
        {
          mx = grid[i, j];
          mn = grid[i, j];
        }
 
        // Calculate for row:
        if(i > 0)
        {
          int tempmx = Math.Max((maxPath[i - 1, j] *
                                 grid[i, j]),
                                (minPath[i - 1, j] *
                                 grid[i, j]));
 
          // Update the maximum
          mx = Math.Max(mx, tempmx);
          int tempmn = Math.Min((maxPath[i - 1, j] *
                                 grid[i, j]),
                                (minPath[i - 1, j] *
                                 grid[i, j]));
 
          // Update the minimum
          mn = Math.Min(mn, tempmn);
        }
 
        // Calculate for column
        if(j > 0)
        {
          int tempmx = Math.Max((maxPath[i, j - 1] *
                                 grid[i, j]),
                                (minPath[i, j - 1] *
                                 grid[i, j]));
 
          // Update the maximum
          mx = Math.Max(mx, tempmx);
          int tempmn = Math.Min((maxPath[i, j - 1] *
                                 grid[i, j]),
                                (minPath[i, j - 1] *
                                 grid[i,j]));
 
          // Update the minimum
          mn = Math.Min(mn, tempmn);
 
        }
 
        // Update maxPath and minPath
        maxPath[i,j] = mx;
        minPath[i,j] = mn;
      }
    }
    // If negative product
    if(maxPath[n - 1, m - 1] < 0)
    {
      return -1;
    }
 
    // Otherwise
    else
    {
      return(maxPath[n - 1, m - 1]);
    }
  }
 
  // Driver Code
  static public void Main ()
  {
 
    // Given matrix mat[][]
    int[,] mat={{1, -2, 1}, {1, -2, 1}, {3, -4, 1}};
 
    // Function Call
    Console.WriteLine(maxProductPath(mat));
  }
}
 
// This code is contributed by avanitrachhadiya2155


Javascript


输出:
8

时间复杂度: O(M*N)
辅助空间: O(M*N)

如果您想与行业专家一起参加直播课程,请参阅Geeks Classes Live