📜  使给定矩阵回文所需的最小增量

📅  最后修改于: 2021-04-22 00:51:45             🧑  作者: Mango

给定尺寸为N * M的矩阵M [] [],任务是找到将矩阵转换为回文矩阵所需的最少1的矩阵元素增量。

例子:

方法:如果arr [0] [0]的值等于X,则arr [M-1] [0]arr [0] [M-1]arr [N-1] [M- 1]的回文性质也必须等于X。所有元素arr [i] [j],arr [N – i – 1] [j],arr [N – i – 1] [M – j – 1],arr [i] [M – j – 1] 。因此,问题减少到找到可以以最小的增量从有关的四元组获得的数量。请按照以下步骤解决问题:

  1. 将矩阵分成4个象限。从(0,0)索引遍历到(((N + 1)/ 2)-1,((M + 1)/ 2)-1)(仅在第一象限中)遍历矩阵。
  2. 对于每个索引(i,j),存储( i,j),(N – i – 1,j),(N – i – 1,M – j – 1),(i,M – j – 1)索引集合,以便仅唯一索引将出现在集合中。
  3. 然后将这些唯一索引中存在的元素存储在向量值中,并评估该向量中的最大值。
  4. 现在,将最大值与向量其余元素之间的差相加并更新ans。

下面是上述方法的实现:

C++
// C++ program for the above approach
#include 
using namespace std;
 
// Function to evaluate minimum number
// of operation required to convert
// the matrix to a palindrome matrix
int palindromeMatrix(int N, int M, vector > arr)
{
    // Variable to store number
    // of operations required
    int ans = 0;
 
    // Iterate over the first
    // quadrant of the matrix
    for (int i = 0; i < (N + 1) / 2; i++) {
 
        for (int j = 0; j < (M + 1) / 2; j++) {
 
            // Store positions of all four
            // values from four quadrants
            set > s;
            s.insert({ i, j });
            s.insert({ i, M - j - 1 });
            s.insert({ N - i - 1, j });
            s.insert({ N - i - 1, M - j - 1 });
 
            // Store the values having
            // unique indexes
            vector values;
            for (pair p : s) {
 
                values.push_back(
                    arr[p.first][p.second]);
            }
 
            // Largest value in the values vector
            int max = *max_element(
                values.begin(),
                values.end());
 
            // Evaluate minimum increments
            // required to make all vector
            // elements equal
            for (int k = 0; k < values.size(); k++) {
 
                ans += max - values[k];
            }
        }
    }
 
    // Print the answer
    cout << ans;
}
 
// Driver Code
int main()
{
    int N = 3, M = 3;
    vector > arr
        = { { 1, 2, 1 },
            { 3, 4, 1 },
            { 1, 2, 1 } };
 
    // Function Call
    palindromeMatrix(N, M, arr);
 
    return 0;
}


Java
// Java program for the
// above approach
import java.util.*;
class GFG{
 
static class pair
{
  int first, second;
  public pair(int first,
              int second) 
  {
    this.first = first;
    this.second = second;
  }   
}
   
// Function to evaluate minimum number
// of operation required to convert
// the matrix to a palindrome matrix
static void palindromeMatrix(int N, int M,
                             int[][] arr)
{
  // Variable to store number
  // of operations required
  int ans = 0;
 
  // Iterate over the first
  // quadrant of the matrix
  for (int i = 0;
           i < (N + 1) / 2; i++)
  {
    for (int j = 0;
             j < (M + 1) / 2; j++)
    {
      // Store positions of all four
      // values from four quadrants
      HashSet s =
              new HashSet<>();
      s.add(new pair(i, j));
      s.add(new pair(i, M - j - 1));
      s.add(new pair(N - i - 1, j));
      s.add(new pair(N - i - 1,
                     M - j - 1));
 
      // Store the values having
      // unique indexes
      Vector values =
             new Vector<>();
      for (pair p : s)
      {
        values.add(
        arr[p.first][p.second]);
      }
 
      // Largest value in the
      // values vector
      int max =
          Collections.max(values);
 
      // Evaluate minimum increments
      // required to make all vector
      // elements equal
      for (int k = 1;
               k < values.size(); k++)
      {
        ans += max - values.get(k);
      }
    }
  }
   
  // Print the answer
  System.out.print(ans);
}
 
// Driver Code
public static void main(String[] args)
{
  int N = 3, M = 3;
  int[][] arr = {{1, 2, 1},
                 {3, 4, 1},
                 {1, 2, 1}};
 
  // Function Call
  palindromeMatrix(N, M, arr);
}
}
 
// This code is contributed by Rajput-Ji


Python3
# Python3 program for the above approach
 
# Function to evaluate minimum number
# of operation required to convert
# the matrix to a palindrome matrix
def palindromeMatrix(N, M, arr):
     
    # Variable to store number
    # of operations required
    ans = 0
 
    # Iterate over the first
    # quadrant of the matrix
    for i in range((N + 1) // 2):
        for j in range((M + 1) // 2):
             
            # Store positions of all four
            # values from four quadrants
            s = {}
            s[(i, j)] = 1
            s[(i, M - j - 1)] = 1
            s[(N - i - 1, j)] = 1
            s[(N - i - 1, M - j - 1)] = 1
 
            # Store the values having
            # unique indexes
            values = []
             
            for p, q in s:
                values.append(arr[p][q])
 
            # Largest value in the values vector
            maxm = max(values)
 
            # Evaluate minimum increments
            # required to make all vector
            # elements equal
            for k in range(len(values)):
                ans += maxm - values[k]
 
    # Print the answer
    print(ans)
 
# Driver Code
if __name__ == '__main__':
     
    N, M = 3, 3
     
    arr = [ [ 1, 2, 1 ],
            [ 3, 4, 1 ],
            [ 1, 2, 1 ] ]
 
    # Function Call
    palindromeMatrix(N, M, arr)
 
# This code is contributed by mohit kumar 29


C#
// C# program for the
// above approach
using System;
using System.Collections.Generic;
 
class GFG{
 
public class pair
{
  public int first, second;
  public pair(int first,
              int second) 
  {
    this.first = first;
    this.second = second;
  }   
}
   
// Function to evaluate minimum number
// of operation required to convert
// the matrix to a palindrome matrix
static void palindromeMatrix(int N, int M,
                             int[,] arr)
{
   
  // Variable to store number
  // of operations required
  int ans = 0;
 
  // Iterate over the first
  // quadrant of the matrix
  for(int i = 0;
          i < (N + 1) / 2; i++)
  {
    for(int j = 0;
            j < (M + 1) / 2; j++)
    {
       
      // Store positions of all four
      // values from four quadrants
      HashSet s = new HashSet();
      s.Add(new pair(i, j));
      s.Add(new pair(i, M - j - 1));
      s.Add(new pair(N - i - 1, j));
      s.Add(new pair(N - i - 1,
                     M - j - 1));
       
      // Store the values having
      // unique indexes
      List values = new List();
       
      foreach (pair p in s)
      {
        values.Add(arr[p.first, p.second]);
      }
 
      // Largest value in the
      // values vector
      values.Sort();
      int max = values[values.Count - 1];
       
      // Evaluate minimum increments
      // required to make all vector
      // elements equal
      for(int k = 1;
              k < values.Count; k++)
      {
        ans += max - values[k];
      }
    }
  }
   
  // Print the answer
  Console.Write(ans);
}
 
// Driver Code
public static void Main(String[] args)
{
  int N = 3, M = 3;
  int[,] arr = { { 1, 2, 1 },
                 { 3, 4, 1 },
                 { 1, 2, 1 } };
 
  // Function Call
  palindromeMatrix(N, M, arr);
}
}
 
// This code is contributed by Amit Katiyar


输出:
2

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