📌  相关文章
📜  计算唯一路径是一个矩阵,其元素乘积包含奇数个除数

📅  最后修改于: 2021-05-17 17:25:55             🧑  作者: Mango

给定尺寸为NxM的矩阵mat [] [] ,任务是计算从左上角的单元(即mat [0] [0]到右下角的单元(即mat [N –给定矩阵的1] [M – 1] ,使得该路径中元素的乘积包含奇数个除数。来自任何像元(i,j)的可能移动是(i,j + 1)(i + 1,j)

例子:

天真的方法:最简单的方法是为给定矩阵生成从左上角单元到右下角单元的所有可能路径,并通过查找所有元素,检查所有此类路径的所有元素的乘积是否具有奇数个除数除数使用本文讨论的方法。

下面是上述方法的实现:

C++
// C++ program for the above approach
#include 
using namespace std;
 
int countPaths = 0;
 
// Store the product of all paths
vector v;
 
// Function to calculate and store
// all the paths product in vector
void CountUniquePaths(int a[][105], int i,
                      int j, int m,
                      int n, int ans)
{
    // Base Case
    if (i >= m || j >= n)
        return;
 
    // If reaches the bottom right
    // corner and product is a
    // perfect square
    if (i == m - 1 && j == n - 1) {
 
        // Find square root
        long double sr = sqrt(ans * a[i][j]);
 
        // If square root is an integer
        if ((sr - floor(sr)) == 0)
            countPaths++;
    }
 
    // Move towards down in the matrix
    CountUniquePaths(a, i + 1, j, m,
                     n, ans * a[i][j]);
 
    // Move towards right in the matrix
    CountUniquePaths(a, i, j + 1, m,
                     n, ans * a[i][j]);
}
 
// Driver Code
int main()
{
    int M = 3, N = 2;
 
    // Given matrix mat[][]
    int mat[M][105] = { { 1, 1 },
                        { 3, 1 },
                        { 3, 1 } };
 
    // Function Call
    CountUniquePaths(mat, 0, 0, M, N, 1);
 
    // Print the result
    cout << countPaths;
 
    return 0;
}


Java
// Java program for the above approach
import java.io.*;
import java.util.*;
import java.lang.*;
 
class GFG{
     
static int countPaths = 0;
 
// Function to calculate and store
// all the paths product in vector
static void CountUniquePaths(int[][] a, int i,
                             int j, int m,
                             int n, int ans)
{
     
    // Base Case
    if (i >= m || j >= n)
        return;
     
    // If reaches the bottom right
    // corner and product is a
    // perfect square
    if (i == m - 1 && j == n - 1)
    {
         
        // Find square root
        double sr = Math.sqrt(ans * a[i][j]);
     
        // If square root is an integer
        if ((sr - Math.floor(sr)) == 0)
            countPaths++;
    }
     
    // Move towards down in the matrix
     CountUniquePaths(a, i + 1, j, m,
                      n, ans * a[i][j]);
     
    // Move towards right in the matrix
     CountUniquePaths(a, i, j + 1, m,
                      n, ans * a[i][j]);
}
 
// Driver Code
public static void main (String[] args)
{
    int M = 3, N = 2;
     
    // Given matrix mat[][]
    int[][] mat = { { 1, 1 },
                    { 3, 1 },
                    { 3, 1 } };
     
    // Function call
    CountUniquePaths(mat, 0, 0, M, N, 1);
     
    System.out.println(countPaths); 
}
}
 
// This code is contributed by sallagondaavinashreddy7


Python3
# Python3 program for
# the above approach
import math 
countPaths = 0;
 
# Function to calculate
# and store all the paths
# product in vector
def CountUniquePaths(a, i, j,
                     m, n, ans):
 
    # Base Case
    if (i >= m or j >= n):
        return;
 
    # If reaches the bottom
    # right corner and product
    # is a perfect square
    global countPaths;
     
    if (i == m - 1 and
        j == n - 1):
 
        # Find square root
        sr = math.sqrt(ans * a[i][j]);
 
        # If square root is an integer
        if ((sr - math.floor(sr)) == 0):
            countPaths += 1;   
 
    # Move towards down
    # in the matrix
    CountUniquePaths(a, i + 1, j,
                     m, n, ans * a[i][j]);
 
    # Move towards right
    # in the matrix
    CountUniquePaths(a, i, j + 1,
                     m, n, ans * a[i][j]);
 
# Driver Code
if __name__ == '__main__':
   
    M = 3; N = 2;
 
    # Given matrix mat
    mat = [[1, 1],
           [3, 1],
           [3, 1]];
 
    # Function call
    CountUniquePaths(mat, 0,
                     0, M, N, 1);
 
    print(countPaths);
 
# This code is contributed by Princi Singh


C#
// C# program for the
// above approach
using System;
class GFG{
     
static int countPaths = 0;
 
// Function to calculate and store
// all the paths product in vector
static void CountUniquePaths(int[,] a, int i,
                             int j, int m,
                             int n, int ans)
{   
  // Base Case
  if (i >= m || j >= n)
    return;
 
  // If reaches the bottom right
  // corner and product is a
  // perfect square
  if (i == m - 1 && j == n - 1)
  {
 
    // Find square root
    double sr = Math.Sqrt(ans *
                          a[i, j]);
 
    // If square root is an integer
    if ((sr - Math.Floor(sr)) == 0)
      countPaths++;
  }
 
  // Move towards down in the matrix
  CountUniquePaths(a, i + 1, j, m,
                   n, ans * a[i, j]);
 
  // Move towards right in the matrix
  CountUniquePaths(a, i, j + 1, m,
                   n, ans * a[i, j]);
}
 
// Driver Code
public static void Main (String[] args)
{
  int M = 3, N = 2;
 
  // Given matrix mat[][]
  int[,] mat = {{1, 1},
                {3, 1},
                {3, 1}};
 
  // Function call
  CountUniquePaths(mat, 0, 0,
                   M, N, 1);
 
  Console.Write(countPaths); 
}
}
 
// This code is contributed by Chitranayal


C++
// C++ program for the above approach
#include 
using namespace std;
 
// Stores the results
vector > >
    dp(105, vector >(105));
 
// Count of unique product paths
int countPaths = 0;
 
// Function to check whether number
// is perfect square or not
bool isPerfectSquare(int n)
{
    long double sr = sqrt(n);
 
    // If square root is an integer
    return ((sr - floor(sr)) == 0);
}
 
// Function to calculate and store
// all the paths product in vector
void countUniquePaths(int a[][105],
                      int m, int n,
                      int ans)
{
    // Store the value a[0][0]
    dp[0][0].push_back(a[0][0]);
 
    // Initialize first row of dp
    for (int i = 1; i < m; i++) {
 
        // Find prefix product
        a[i][0] *= a[i - 1][0];
        dp[i][0].push_back(a[i][0]);
    }
 
    // Initialize first column of dp
    for (int i = 1; i < n; i++) {
 
        // Find the prefix product
        a[0][i] *= a[0][i - 1];
        dp[0][i].push_back(a[0][i]);
    }
 
    // Iterate over range (1, 1) to (N, M)
    for (int i = 1; i < m; i++) {
        for (int j = 1; j < n; j++) {
 
            // Copy  dp[i-1][j] in top[]
            vector top = dp[i - 1][j];
 
            // Copy dp[i][j-1] into left[]
            vector left = dp[i][j - 1];
 
            // Compute the values of current
            // state and store it in curr[]
            vector curr;
 
            // Find the product of a[i][j]
            // with elements at top[]
            for (int k = 0;
                 k < top.size(); k++) {
                curr.push_back(top[k] * a[i][j]);
            }
 
            // Find the product of a[i][j]
            // with elements at left[]
            for (int k = 0;
                 k < left.size(); k++) {
                curr.push_back(left[k] * a[i][j]);
            }
 
            // Update the current state
            dp[i][j] = curr;
        }
    }
 
    // Traverse dp[m - 1][n - 1]
    for (auto i : dp[m - 1][n - 1]) {
 
        // Check if perfect square
        if (isPerfectSquare(i)) {
            countPaths++;
        }
    }
}
 
// Driver Code
int main()
{
    int M = 3, N = 4;
 
    // Given matrix mat[][]
    int mat[M][105] = { { 1, 2, 3, 1 },
                        { 3, 1, 2, 4 },
                        { 2, 3, 1, 1 } };
 
    // Function Call
    countUniquePaths(mat, M, N, 1);
 
    // Print the final count
    cout << countPaths;
 
    return 0;
}


Java
// Java program to implement 
// the above approach
import java.util.*;
class GFG
{
 
  // Stores the results
  static ArrayList>> dp;
 
  // Count of unique product paths
  static int countPaths = 0;
 
  // Function to check whether number
  // is perfect square or not
  static boolean isPerfectSquare(int n)
  {
    double  sr = Math.sqrt(n);
 
    // If square root is an integer
    return ((sr - Math.floor(sr)) == 0);
  }
 
  // Function to calculate and store
  // all the paths product in vector
  static void countUniquePaths(int a[][],
                               int m, int n,
                               int ans)
  {
 
    // Store the value a[0][0]
    dp.get(0).get(0).add(a[0][0]);
 
    // Initialize first row of dp
    for (int i = 1; i < m; i++)
    {
 
      // Find prefix product
      a[i][0] *= a[i - 1][0];
      dp.get(i).get(0).add(a[i][0]);
    }
 
    // Initialize first column of dp
    for (int i = 1; i < n; i++)
    {
 
      // Find the prefix product
      a[0][i] *= a[0][i - 1];
      dp.get(0).get(i).add(a[0][i]);
    }
 
    // Iterate over range (1, 1) to (N, M)
    for (int i = 1; i < m; i++)
    {
      for (int j = 1; j < n; j++)
      {
 
        // Copy  dp[i-1][j] in top[]
        ArrayList top =
          dp.get(i - 1).get(j);
 
        // Copy dp[i][j-1] into left[]
        ArrayList left =
          dp.get(i).get(j - 1);
 
        // Compute the values of current
        // state and store it in curr[]
        ArrayList curr = new ArrayList<>();
 
        // Find the product of a[i][j]
        // with elements at top[]
        for (int k = 0;
             k < top.size(); k++)
        {
          curr.add(top.get(k) * a[i][j]);
        }
 
        // Find the product of a[i][j]
        // with elements at left[]
        for (int k = 0;
             k < left.size(); k++)
        {
          curr.add(left.get(k) * a[i][j]);
        }
 
        // Update the current state
        dp.get(i).set(j, curr);
      }
    }
 
    // Traverse dp[m - 1][n - 1]
    for (Integer i : dp.get(m - 1).get(n - 1))
    {
 
      // Check if perfect square
      if (isPerfectSquare(i))
      {
        countPaths++;
      }
    }
  }
 
  // Driver code
  public static void main (String[] args)
  {
    int M = 3, N = 4;
 
    // Given matrix mat[][]
    int mat[][] = { { 1, 2, 3, 1 },
                   { 3, 1, 2, 4 },
                   { 2, 3, 1, 1 } };
 
    dp = new ArrayList<>();
 
    for(int i = 0; i < 105; i++)
    {
      dp.add(new ArrayList<>());
      for(int j = 0; j < 105; j++)
        dp.get(i).add(new ArrayList());
    }
 
    // Function Call
    countUniquePaths(mat, M, N, 1);
 
    // Print the final count
    System.out.println(countPaths);
  }
}
 
// This code is contributed by offbeat


Python3
# Python3 program for the above approach
from math import sqrt, floor
 
# Stores the results
dp = [[[] for j in range(105)]
          for k in range(105)]
 
# Count of unique product paths
countPaths = 0
 
# Function to check whether number
# is perfect square or not
def isPerfectSquare(n):
     
    sr = sqrt(n)
 
    # If square root is an integer
    return ((sr - floor(sr)) == 0)
 
# Function to calculate and store
# all the paths product in vector
def countUniquePaths(a, m, n, ans):
     
    global dp
    global countPaths
     
    # Store the value a[0][0]
    dp[0][0].append(a[0][0])
 
    # Initialize first row of dp
    for i in range(1, m):
         
        # Find prefix product
        a[i][0] *= a[i - 1][0]
        dp[i][0].append(a[i][0])
 
    # Initialize first column of dp
    for i in range(1, n):
         
        # Find the prefix product
        a[0][i] *= a[0][i - 1]
        dp[0][i].append(a[0][i])
 
    # Iterate over range (1, 1) to (N, M)
    for i in range(1, m):
        for j in range(1, n):
             
            # Copy  dp[i-1][j] in top[]
            top = dp[i - 1][j]
 
            # Copy dp[i][j-1] into left[]
            left = dp[i][j - 1]
 
            # Compute the values of current
            # state and store it in curr[]
            curr = []
 
            # Find the product of a[i][j]
            # with elements at top[]
            for k in range(len(top)):
                curr.append(top[k] * a[i][j])
 
            # Find the product of a[i][j]
            # with elements at left[]
            for k in range(len(left)):
                curr.append(left[k] * a[i][j])
 
            # Update the current state
            dp[i][j] = curr
 
    # Traverse dp[m - 1][n - 1]
    for i in dp[m - 1][n - 1]:
         
        # Check if perfect square
        if (isPerfectSquare(i)):
            countPaths += 1
 
# Driver Code
if __name__ == '__main__':
     
    M = 3
    N = 4
 
    # Given matrix mat[][]
    mat = [ [ 1, 2, 3, 1 ],
            [ 3, 1, 2, 4 ],
            [ 2, 3, 1, 1 ] ]
 
    # Function Call
    countUniquePaths(mat, M, N, 1)
 
    # Print the final count
    print(countPaths)
 
# This code is contributed by ipg2016107


输出:
2

时间复杂度: O((2 N )* sqrt(N))
辅助空间: O(1)

高效方法:为了优化上述方法,其思想是使用动态编程。初始化辅助空间dp [] [] [] ,该空间将存储具有给定矩阵每一行从每行的左上角到行尾的所有路径的乘积的数字。步骤如下:

  • 初始化3D辅助空间dp [] [] [] ,其中dp [i] [j]将存储从单元格(0,0)(i,j)的所有路径的乘积。
  • 要计算每个状态值,请使用dp(i – 1,j)dp(i,j – 1)中的所有值来计算dp [i] [j]。
  • 对于给定矩阵的第一行, mat [] []将第一行的前缀乘积存储在dp [i] [0]处
  • 对于给定矩阵的第一列, mat [] []将第一列的前缀乘积存储在dp [0] [i]处
  • 现在使用两个嵌套循环ij( 1,1)迭代到(N,M)并执行以下操作:
    • 将向量的顶部存储在索引dp [i – 1] [j]处,将其左侧存储在索引dp [i] [j – 1]处
    • 将当前元素mat [i] [j]与元素分别存储在top []left []中的乘积存储在另一个辅助数组curr []中
    • 将当前dp状态更新为dp [i] [j] = curr
  • 现在遍历存储在dp(N – 1,M – 1)处的数组并计算所有数字,这是一个理想的平方。
  • 完成上述步骤后,打印最终计数。

下面是上述方法的实现:

C++

// C++ program for the above approach
#include 
using namespace std;
 
// Stores the results
vector > >
    dp(105, vector >(105));
 
// Count of unique product paths
int countPaths = 0;
 
// Function to check whether number
// is perfect square or not
bool isPerfectSquare(int n)
{
    long double sr = sqrt(n);
 
    // If square root is an integer
    return ((sr - floor(sr)) == 0);
}
 
// Function to calculate and store
// all the paths product in vector
void countUniquePaths(int a[][105],
                      int m, int n,
                      int ans)
{
    // Store the value a[0][0]
    dp[0][0].push_back(a[0][0]);
 
    // Initialize first row of dp
    for (int i = 1; i < m; i++) {
 
        // Find prefix product
        a[i][0] *= a[i - 1][0];
        dp[i][0].push_back(a[i][0]);
    }
 
    // Initialize first column of dp
    for (int i = 1; i < n; i++) {
 
        // Find the prefix product
        a[0][i] *= a[0][i - 1];
        dp[0][i].push_back(a[0][i]);
    }
 
    // Iterate over range (1, 1) to (N, M)
    for (int i = 1; i < m; i++) {
        for (int j = 1; j < n; j++) {
 
            // Copy  dp[i-1][j] in top[]
            vector top = dp[i - 1][j];
 
            // Copy dp[i][j-1] into left[]
            vector left = dp[i][j - 1];
 
            // Compute the values of current
            // state and store it in curr[]
            vector curr;
 
            // Find the product of a[i][j]
            // with elements at top[]
            for (int k = 0;
                 k < top.size(); k++) {
                curr.push_back(top[k] * a[i][j]);
            }
 
            // Find the product of a[i][j]
            // with elements at left[]
            for (int k = 0;
                 k < left.size(); k++) {
                curr.push_back(left[k] * a[i][j]);
            }
 
            // Update the current state
            dp[i][j] = curr;
        }
    }
 
    // Traverse dp[m - 1][n - 1]
    for (auto i : dp[m - 1][n - 1]) {
 
        // Check if perfect square
        if (isPerfectSquare(i)) {
            countPaths++;
        }
    }
}
 
// Driver Code
int main()
{
    int M = 3, N = 4;
 
    // Given matrix mat[][]
    int mat[M][105] = { { 1, 2, 3, 1 },
                        { 3, 1, 2, 4 },
                        { 2, 3, 1, 1 } };
 
    // Function Call
    countUniquePaths(mat, M, N, 1);
 
    // Print the final count
    cout << countPaths;
 
    return 0;
}

Java

// Java program to implement 
// the above approach
import java.util.*;
class GFG
{
 
  // Stores the results
  static ArrayList>> dp;
 
  // Count of unique product paths
  static int countPaths = 0;
 
  // Function to check whether number
  // is perfect square or not
  static boolean isPerfectSquare(int n)
  {
    double  sr = Math.sqrt(n);
 
    // If square root is an integer
    return ((sr - Math.floor(sr)) == 0);
  }
 
  // Function to calculate and store
  // all the paths product in vector
  static void countUniquePaths(int a[][],
                               int m, int n,
                               int ans)
  {
 
    // Store the value a[0][0]
    dp.get(0).get(0).add(a[0][0]);
 
    // Initialize first row of dp
    for (int i = 1; i < m; i++)
    {
 
      // Find prefix product
      a[i][0] *= a[i - 1][0];
      dp.get(i).get(0).add(a[i][0]);
    }
 
    // Initialize first column of dp
    for (int i = 1; i < n; i++)
    {
 
      // Find the prefix product
      a[0][i] *= a[0][i - 1];
      dp.get(0).get(i).add(a[0][i]);
    }
 
    // Iterate over range (1, 1) to (N, M)
    for (int i = 1; i < m; i++)
    {
      for (int j = 1; j < n; j++)
      {
 
        // Copy  dp[i-1][j] in top[]
        ArrayList top =
          dp.get(i - 1).get(j);
 
        // Copy dp[i][j-1] into left[]
        ArrayList left =
          dp.get(i).get(j - 1);
 
        // Compute the values of current
        // state and store it in curr[]
        ArrayList curr = new ArrayList<>();
 
        // Find the product of a[i][j]
        // with elements at top[]
        for (int k = 0;
             k < top.size(); k++)
        {
          curr.add(top.get(k) * a[i][j]);
        }
 
        // Find the product of a[i][j]
        // with elements at left[]
        for (int k = 0;
             k < left.size(); k++)
        {
          curr.add(left.get(k) * a[i][j]);
        }
 
        // Update the current state
        dp.get(i).set(j, curr);
      }
    }
 
    // Traverse dp[m - 1][n - 1]
    for (Integer i : dp.get(m - 1).get(n - 1))
    {
 
      // Check if perfect square
      if (isPerfectSquare(i))
      {
        countPaths++;
      }
    }
  }
 
  // Driver code
  public static void main (String[] args)
  {
    int M = 3, N = 4;
 
    // Given matrix mat[][]
    int mat[][] = { { 1, 2, 3, 1 },
                   { 3, 1, 2, 4 },
                   { 2, 3, 1, 1 } };
 
    dp = new ArrayList<>();
 
    for(int i = 0; i < 105; i++)
    {
      dp.add(new ArrayList<>());
      for(int j = 0; j < 105; j++)
        dp.get(i).add(new ArrayList());
    }
 
    // Function Call
    countUniquePaths(mat, M, N, 1);
 
    // Print the final count
    System.out.println(countPaths);
  }
}
 
// This code is contributed by offbeat

Python3

# Python3 program for the above approach
from math import sqrt, floor
 
# Stores the results
dp = [[[] for j in range(105)]
          for k in range(105)]
 
# Count of unique product paths
countPaths = 0
 
# Function to check whether number
# is perfect square or not
def isPerfectSquare(n):
     
    sr = sqrt(n)
 
    # If square root is an integer
    return ((sr - floor(sr)) == 0)
 
# Function to calculate and store
# all the paths product in vector
def countUniquePaths(a, m, n, ans):
     
    global dp
    global countPaths
     
    # Store the value a[0][0]
    dp[0][0].append(a[0][0])
 
    # Initialize first row of dp
    for i in range(1, m):
         
        # Find prefix product
        a[i][0] *= a[i - 1][0]
        dp[i][0].append(a[i][0])
 
    # Initialize first column of dp
    for i in range(1, n):
         
        # Find the prefix product
        a[0][i] *= a[0][i - 1]
        dp[0][i].append(a[0][i])
 
    # Iterate over range (1, 1) to (N, M)
    for i in range(1, m):
        for j in range(1, n):
             
            # Copy  dp[i-1][j] in top[]
            top = dp[i - 1][j]
 
            # Copy dp[i][j-1] into left[]
            left = dp[i][j - 1]
 
            # Compute the values of current
            # state and store it in curr[]
            curr = []
 
            # Find the product of a[i][j]
            # with elements at top[]
            for k in range(len(top)):
                curr.append(top[k] * a[i][j])
 
            # Find the product of a[i][j]
            # with elements at left[]
            for k in range(len(left)):
                curr.append(left[k] * a[i][j])
 
            # Update the current state
            dp[i][j] = curr
 
    # Traverse dp[m - 1][n - 1]
    for i in dp[m - 1][n - 1]:
         
        # Check if perfect square
        if (isPerfectSquare(i)):
            countPaths += 1
 
# Driver Code
if __name__ == '__main__':
     
    M = 3
    N = 4
 
    # Given matrix mat[][]
    mat = [ [ 1, 2, 3, 1 ],
            [ 3, 1, 2, 4 ],
            [ 2, 3, 1, 1 ] ]
 
    # Function Call
    countUniquePaths(mat, M, N, 1)
 
    # Print the final count
    print(countPaths)
 
# This code is contributed by ipg2016107
输出:
3

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