Minimum increments required to make given matrix palindromic

Given a matrix M[][] of dimensions N * M, the task is to find the minimum number of increments of matrix elements by 1 required to convert the matrix to a palindromic matrix.

A palindrome matrix is a matrix in which every row and column is a palindrome
 

Example:

Input: N = 4, M = 2, arr[][]={{5, 3}, {3, 5}, {5, 3}, {3, 5}}
Output: 8
Explanation: The palindromic matrix will be arr[][] = {{5, 5}, {5, 5}, {5, 5}, {5, 5}}

Input: N = 3, M = 3, arr[][]={{1, 2, 1}, {3, 4, 1}, {1, 2, 1}}
Output: 2
Explanation:
The palindromic matrix will be arr[][] = {{1, 2, 1}, {3, 4, 3}, {1, 2, 1}}



Approach: If the value of arr[0][0] is equal X, then values of arr[M-1][0], arr[0][M-1], and arr[N-1][M-1] must also be equal to X by the palindrome property. A similar property holds for all the elements arr[i][j], arr[N – i – 1][j], arr[N – i – 1][M – j – 1], arr[i][M – j – 1] as well. Therefore, the problem reduces to finding the number that can be obtained from the concerned quadruples with minimum increments. Follow the steps below to solve the problem:

  1. Divide the matrix into 4 quadrants. Traverse over the matrix from (0, 0) index to (((N + 1) / 2)-1, ((M + 1) / 2)-1) (Only in the first quadrant).
  2. For each index (i, j) store (i, j), (N – i – 1, j), (N – i – 1, M – j – 1), (i, M – j – 1) indexes in a set so that only unique indexes will be present in the set.
  3. Then store the elements present in those unique indexes in vector values and evaluate the maximum in this vector.
  4. Now add the difference between the maximum value and the rest of the elements of the values vector and update the ans.

Below is the implementation of the above approach:

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program for the above approach
#include <bits/stdc++.h>
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<vector<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
            set<pair<int, int> > 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<int> values;
            for (pair<int, int> 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<vector<int> > arr
        = { { 1, 2, 1 },
            { 3, 4, 1 },
            { 1, 2, 1 } };
 
    // Function Call
    palindromeMatrix(N, M, arr);
 
    return 0;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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<pair> 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<Integer> 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

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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<pair> s = new HashSet<pair>();
      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<int> values = new List<int>();
       
      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

chevron_right


Output: 

2








 

Time Complexity: O(N * M)
Auxiliary Space: O(1)

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.




My Personal Notes arrow_drop_up

Recommended Posts:


Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



Improved By : Rajput-Ji, amit143katiyar