📌  相关文章
📜  将 Matrix 中所有左上角到右下角路径转换为回文的最小步骤 | 2套

📅  最后修改于: 2021-09-05 08:28:30             🧑  作者: Mango

给定一个矩阵mat[][]N行和M列。任务是找到矩阵中所需的最小更改次数,使得从左上角到右下角的每条路径都是回文路径。在路径中,只允许从一个单元格到另一个单元格的向右和底部移动。

例子:

朴素的方法:关于朴素的方法,请参考这篇文章。

高效的方法:这个想法是丢弃使用 HashMap 的额外空间。请按照以下步骤操作:

  1. 从左上角和右下角可能的距离在0 到 N + M – 2的范围内。因此,创建一个维度为[N + M – 1][10]的二维数组。
  2. 将距离的频率存储在数组中,同时将行号(范围 0 到 N + M – 2)视为距离,将列号(0 到 9)视为给定矩阵中的元素。
  3. 用于改变的次数为最小,更改在距离X的每个细胞与具有距离X的所有值中的最高频率的值。
  4. 所需的最小步数是每个距离的频率总值与频率最大值的差值之和。

下面是上述方法的实现:

C++
// C++ program for the above approach
#include 
using namespace std;
#define N 7
  
// Function for counting minimum
// number of changes
int countChanges(int matrix[][N],
                 int n, int m)
{
    // Distance of elements from (0, 0)
    // will is i range [0, n + m - 2]
    int dist = n + m - 1;
  
    // Store frequencies of [0, 9]
    // at distance i
    int freq[dist][10];
  
    // Initialize frequencies as 0
    for (int i = 0; i < dist; i++) {
        for (int j = 0; j < 10; j++)
            freq[i][j] = 0;
    }
  
    // Count frequencies of [0, 9]
    for (int i = 0; i < n; i++) {
  
        for (int j = 0; j < m; j++) {
  
            // Increment frequency of
            // value matrix[i][j]
            // at distance i+j
            freq[i + j][matrix[i][j]]++;
        }
    }
  
    int min_changes_sum = 0;
    for (int i = 0; i < dist / 2; i++) {
  
        int maximum = 0;
        int total_values = 0;
  
        // Find value with max frequency
        // and count total cells at distance i
        // from front end and rear end
        for (int j = 0; j < 10; j++) {
  
            maximum = max(maximum, freq[i][j]
                    + freq[n + m - 2 - i][j]);
  
            total_values += (freq[i][j]
                   + freq[n + m - 2 - i][j]);
        }
  
        // Change all values to the
        // value with max frequency
        min_changes_sum += (total_values
                            - maximum);
    }
  
    // Return the answer
    return min_changes_sum;
}
  
// Driver Code
int main()
{
    // Given Matrix
    int mat[][N] = { { 1, 2 }, { 3, 5 } };
  
    // Function Call
    cout << countChanges(mat, 2, 2);
    return 0;
}


Java
// Java program for the above approach
import java.util.*;
  
class GFG{
      
static final int N = 7;
  
// Function for counting minimum
// number of changes
static int countChanges(int matrix[][],
                        int n, int m)
{
      
    // Distance of elements from (0, 0)
    // will is i range [0, n + m - 2]
    int dist = n + m - 1;
  
    // Store frequencies of [0, 9]
    // at distance i
    int [][]freq = new int[dist][10];
  
    // Initialize frequencies as 0
    for(int i = 0; i < dist; i++)
    {
        for(int j = 0; j < 10; j++)
            freq[i][j] = 0;
    }
  
    // Count frequencies of [0, 9]
    for(int i = 0; i < n; i++) 
    {
        for(int j = 0; j < m; j++)
        {
              
            // Increment frequency of
            // value matrix[i][j]
            // at distance i+j
            freq[i + j][matrix[i][j]]++;
        }
    }
  
    int min_changes_sum = 0;
    for(int i = 0; i < dist / 2; i++) 
    {
        int maximum = 0;
        int total_values = 0;
  
        // Find value with max frequency
        // and count total cells at distance i
        // from front end and rear end
        for(int j = 0; j < 10; j++) 
        {
            maximum = Math.max(maximum, freq[i][j] +
                            freq[n + m - 2 - i][j]);
  
            total_values += (freq[i][j] + 
                             freq[n + m - 2 - i][j]);
        }
          
        // Change all values to the
        // value with max frequency
        min_changes_sum += (total_values -
                            maximum);
    }
  
    // Return the answer
    return min_changes_sum;
}
  
// Driver Code
public static void main(String[] args)
{
      
    // Given matrix
    int mat[][] = { { 1, 2 }, { 3, 5 } };
  
    // Function call
    System.out.print(countChanges(mat, 2, 2));
}
}
  
// This code is contributed by Rohit_ranjan


Python3
# Python3 program for the above approach
  
# Function for counting minimum 
# number of changes
def countChanges(matrix, n, m):
  
    # Distance of elements from (0, 0) 
    # will is i range [0, n + m - 2] 
    dist = n + m - 1
  
    # Store frequencies of [0, 9] 
    # at distance i 
    # Initialize all with zero
    freq = [[0] * 10 for i in range(dist)]
  
    # Count frequencies of [0, 9]
    for i in range(n):
        for j in range(m):
  
            # Increment frequency of 
            # value matrix[i][j] 
            # at distance i+j 
            freq[i + j][matrix[i][j]] += 1
  
    min_changes_sum = 0
  
    for i in range(dist // 2):
        maximum = 0
        total_values = 0
  
        # Find value with max frequency 
        # and count total cells at distance i 
        # from front end and rear end         
        for j in range(10):
            maximum = max(maximum, freq[i][j] +
                       freq[n + m - 2 - i][j])
  
            total_values += (freq[i][j] +
                 freq[n + m - 2 - i][j])
  
        # Change all values to the value
        # with max frequency
        min_changes_sum += (total_values -
                            maximum)
                              
    # Return the answer
    return min_changes_sum
  
# Driver code
if __name__ == '__main__':
  
    # Given matrix
    mat = [ [ 1, 2 ], [ 3, 5 ] ]
  
    # Function call
    print(countChanges(mat, 2, 2))
  
# This code is contributed by himanshu77


C#
// C# program for the above approach
using System;
  
class GFG{
      
//static readonly int N = 7;
  
// Function for counting minimum
// number of changes
static int countChanges(int [,]matrix,
                        int n, int m)
{
      
    // Distance of elements from (0, 0)
    // will is i range [0, n + m - 2]
    int dist = n + m - 1;
  
    // Store frequencies of [0, 9]
    // at distance i
    int [,]freq = new int[dist, 10];
  
    // Initialize frequencies as 0
    for(int i = 0; i < dist; i++)
    {
        for(int j = 0; j < 10; j++)
            freq[i, j] = 0;
    }
  
    // Count frequencies of [0, 9]
    for(int i = 0; i < n; i++) 
    {
        for(int j = 0; j < m; j++)
        {
              
            // Increment frequency of
            // value matrix[i,j]
            // at distance i+j
            freq[i + j, matrix[i, j]]++;
        }
    }
  
    int min_changes_sum = 0;
    for(int i = 0; i < dist / 2; i++) 
    {
        int maximum = 0;
        int total_values = 0;
  
        // Find value with max frequency
        // and count total cells at distance i
        // from front end and rear end
        for(int j = 0; j < 10; j++) 
        {
            maximum = Math.Max(maximum, freq[i, j] +
                            freq[n + m - 2 - i, j]);
  
            total_values += (freq[i, j] + 
                             freq[n + m - 2 - i, j]);
        }
          
        // Change all values to the
        // value with max frequency
        min_changes_sum += (total_values -
                            maximum);
    }
  
    // Return the answer
    return min_changes_sum;
}
  
// Driver Code
public static void Main(String[] args)
{
      
    // Given matrix
    int [,]mat = { { 1, 2 }, { 3, 5 } };
  
    // Function call
    Console.Write(countChanges(mat, 2, 2));
}
}
  
// This code is contributed by Rohit_ranjan


输出:
1

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

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