📌  相关文章
📜  使矩阵回文中的每条路径所需的最小更改

📅  最后修改于: 2021-04-25 01:09:02             🧑  作者: Mango

给定一个具有N行和M列的矩阵,任务是通过最小化单元格值的变化,使从单元格(N,M)(1,1)回文的所有可能路径成为可能。

例子:

方法:

  • 如果最后一个单元格的值等于第一个单元格的值,第二个最后一个单元格的值等于第二个单元格的值,则将路径称为回文路径,依此类推。
  • 因此,我们可以得出结论,要使路径回文,距( N,M)的距离(Manhatten距离) x处的像元必须等于距(1,1)的距离x的像元。
  • 为了最大程度地减少更改次数,请将距离( x(1,1)(N,M))的每个单元格转换为这些单元格中所有值中最频繁的单元格。

下面是上述方法的实现。

C++
// C++ Program to implement the
// above approach
#include 
using namespace std;
 
#define N 7
 
// Function for counting changes
int countChanges(int matrix[][N],
                 int n, int m)
{
    // Maximum distance possible
    // is (n - 1 + m - 1)
    int dist = n + m - 1;
 
    // Stores the maximum element
    int Max_element = 0;
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < m; j++) {
            // Update the maximum
            Max_element = max(Max_element,
                              matrix[i][j]);
        }
    }
 
    // Stores frequencies of
    // values for respective
    // distances
    int freq[dist][Max_element + 1];
 
    // Initialize frequencies of
    // cells as 0
    for (int i = 0; i < dist; i++) {
        for (int j = 0; j < Max_element + 1;
             j++)
            freq[i][j] = 0;
    }
 
    // Count frequencies of cell
    // values in the matrix
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < m; j++) {
 
            // Increment frequency of
            // value at distance i+j
            freq[i + j][matrix[i][j]]++;
        }
    }
 
    int min_changes_sum = 0;
    for (int i = 0; i < dist / 2; i++) {
 
        // Store the most frequent
        // value at i-th distance
        // from (0, 0) and (N - 1, M - 1)
        int maximum = 0;
        int total_values = 0;
 
        // Calculate max frequency
        // and total cells at distance i
        for (int j = 0; j < Max_element + 1;
             j++) {
 
            maximum
                = max(maximum,
                      freq[i][j]
                          + freq[n + m - 2
                                 - i][j]);
 
            total_values
                += freq[i][j]
                   + freq[n + m - 2 - i][j];
        }
 
        // Count changes required
        // to convert all cells
        // at i-th distance to
        // most frequent value
        min_changes_sum
            += total_values - maximum;
    }
 
    return min_changes_sum;
}
 
// Driver Code
int main()
{
    int mat[][N] = { { 7, 0, 3, 1, 8, 1, 3 },
                     { 0, 4, 0, 1, 0, 4, 0 },
                     { 3, 1, 8, 3, 1, 0, 7 } };
 
    int minChanges = countChanges(mat, 3, 7);
 
    cout << minChanges;
 
    return 0;
}


Java
// Java program to implement the
// above approach
import java.util.*;
 
class GFG{
static int N = 7;
 
// Function for counting changes
static int countChanges(int matrix[][],
                        int n, int m)
{
     
    // Maximum distance possible
    // is (n - 1 + m - 1)
    int i, j, dist = n + m - 1;
 
    // Stores the maximum element
    int Max_element = 0;
    for(i = 0; i < n; i++)
    {
        for(j = 0; j < m; j++)
        {
             
            // Update the maximum
            Max_element = Math.max(Max_element,
                                   matrix[i][j]);
        }
    }
 
    // Stores frequencies of
    // values for respective
    // distances
    int freq[][] = new int[dist][Max_element + 1];
 
    // Initialize frequencies of
    // cells as 0
    for(i = 0; i < dist; i++)
    {
        for(j = 0; j < Max_element + 1;
            j++)
            freq[i][j] = 0;
    }
 
    // Count frequencies of cell
    // values in the matrix
    for(i = 0; i < n; i++)
    {
        for(j = 0; j < m; j++)
        {
             
            // Increment frequency of
            // value at distance i+j
            freq[i + j][matrix[i][j]]++;
        }
    }
     
    int min_changes_sum = 0;
    for(i = 0; i < dist / 2; i++)
    {
         
        // Store the most frequent
        // value at i-th distance
        // from (0, 0) and (N - 1, M - 1)
        int maximum = 0;
        int total_values = 0;
 
        // Calculate max frequency
        // and total cells at distance i
        for(j = 0; j < Max_element + 1; 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];
        }
 
        // Count changes required
        // to convert all cells
        // at i-th distance to
        // most frequent value
        min_changes_sum += total_values -
                           maximum;
    }
    return min_changes_sum;
}
 
// Driver Code
public static void main (String []args)
{
    int mat[][] = { { 7, 0, 3, 1, 8, 1, 3 },
                    { 0, 4, 0, 1, 0, 4, 0 },
                    { 3, 1, 8, 3, 1, 0, 7 } };
 
    int minChanges = countChanges(mat, 3, 7);
 
    System.out.print(minChanges);
}
}
 
// This code is contributed by chitranayal


Python3
# Python3 program to implement the
# above approach
 
# Function for counting changes
def countChanges(matrix, n, m):
 
    # Maximum distance possible
    # is (n - 1 + m - 1)
    dist = n + m - 1
 
    # Stores the maximum element
    Max_element = 0
    for i in range(n):
        for j in range(m):
             
            # Update the maximum
            Max_element = max(Max_element,
                              matrix[i][j])
 
    # Stores frequencies of
    # values for respective
    # distances
    freq = [[0 for i in range(Max_element + 1)]
               for j in range(dist)]
 
    # Initialize frequencies of
    # cells as 0
    for i in range(dist):
        for j in range(Max_element + 1):
            freq[i][j] = 0
 
    # Count frequencies of cell
    # values in the matrix
    for i in range(n):
        for j in range(m):
 
            # Increment frequency of
            # value at distance i+j
            freq[i + j][matrix[i][j]] += 1
 
    min_changes_sum = 0
    for i in range(dist // 2):
 
        # Store the most frequent
        # value at i-th distance
        # from (0, 0) and (N - 1, M - 1)
        maximum = 0
        total_values = 0
 
        # Calculate max frequency
        # and total cells at distance i
        for j in range(Max_element + 1):
            maximum = max(maximum,
                          freq[i][j] +
                          freq[n + m - 2 - i][j])
 
            total_values += (freq[i][j] +
                             freq[n + m - 2 - i][j])
 
        # Count changes required
        # to convert all cells
        # at i-th distance to
        # most frequent value
        min_changes_sum += total_values - maximum
 
    return min_changes_sum
 
# Driver code
if __name__ == '__main__':
 
    mat = [ [ 7, 0, 3, 1, 8, 1, 3 ],
            [ 0, 4, 0, 1, 0, 4, 0 ],
            [ 3, 1, 8, 3, 1, 0, 7 ] ]
 
    minChanges = countChanges(mat, 3, 7)
 
    print(minChanges)
 
# This code is contributed by Shivam Singh


C#
// C# program to implement the
// above approach
using System;
class GFG{
   
//static int N = 7;
 
// Function for counting changes
static int countChanges(int [,]matrix,
                        int n, int m)
{
     
    // Maximum distance possible
    // is (n - 1 + m - 1)
    int i, j, dist = n + m - 1;
 
    // Stores the maximum element
    int Max_element = 0;
    for(i = 0; i < n; i++)
    {
        for(j = 0; j < m; j++)
        {
             
            // Update the maximum
            Max_element = Math.Max(Max_element,
                                   matrix[i, j]);
        }
    }
 
    // Stores frequencies of
    // values for respective
    // distances
    int [,]freq = new int[dist, Max_element + 1];
 
    // Initialize frequencies of
    // cells as 0
    for(i = 0; i < dist; i++)
    {
        for(j = 0; j < Max_element + 1;
            j++)
            freq[i, j] = 0;
    }
 
    // Count frequencies of cell
    // values in the matrix
    for(i = 0; i < n; i++)
    {
        for(j = 0; j < m; j++)
        {
             
            // Increment frequency of
            // value at distance i+j
            freq[i + j, matrix[i, j]]++;
        }
    }
     
    int min_changes_sum = 0;
    for(i = 0; i < dist / 2; i++)
    {
         
        // Store the most frequent
        // value at i-th distance
        // from (0, 0) and (N - 1, M - 1)
        int maximum = 0;
        int total_values = 0;
 
        // Calculate max frequency
        // and total cells at distance i
        for(j = 0; j < Max_element + 1; 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];
        }
 
        // Count changes required
        // to convert all cells
        // at i-th distance to
        // most frequent value
        min_changes_sum += total_values -
                           maximum;
    }
    return min_changes_sum;
}
 
// Driver Code
public static void Main(String []args)
{
    int [,]mat = { { 7, 0, 3, 1, 8, 1, 3 },
                    { 0, 4, 0, 1, 0, 4, 0 },
                    { 3, 1, 8, 3, 1, 0, 7 } };
 
    int minChanges = countChanges(mat, 3, 7);
 
    Console.Write(minChanges);
}
}
 
// This code is contributed by sapnasingh4991


输出:
6



时间复杂度: O(N * M)
辅助空间: O((N + M)* maxm),其中maxm是矩阵中存在的最大元素。