Minimum increments required to make given matrix palindromic
Last Updated :
22 Jun, 2021
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:
- 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).
- 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.
- Then store the elements present in those unique indexes in vector values and evaluate the maximum in this vector.
- 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++
// 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;
}
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<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
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<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
JavaScript
<script>
// Javascript program for the
// above approach
class pair
{
constructor(first, second)
{
this.first = first;
this.second = second;
}
}
// Function to evaluate minimum number
// of operation required to convert
// the matrix to a palindrome matrix
function palindromeMatrix(N, M, arr)
{
// Variable to store number
// of operations required
let ans = 0;
// Iterate over the first
// quadrant of the matrix
for (let i = 0;
i < Math.floor((N + 1) / 2); i++)
{
for (let j = 0;
j < Math.floor((M + 1) / 2); j++)
{
// Store positions of all four
// values from four quadrants
let s = new Set();
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
let values = [];
for (let p of s.values())
{
values.push(
arr[p.first][p.second]);
}
values.sort(function(a,b){return a-b;});
// Largest value in the
// values vector
let max =Math.max(...values);
// Evaluate minimum increments
// required to make all vector
// elements equal
for (let k = 1;
k < values.length; k++)
{
ans += max - values[k];
}
}
}
// Print the answer
document.write(ans);
}
// Driver Code
let N = 3, M = 3;
let arr=[[1, 2, 1],
[3, 4, 1],
[1, 2, 1]];
// Function Call
palindromeMatrix(N, M, arr);
// This code is contributed by patel2127
</script>
Time Complexity: O(N * M)
Auxiliary Space: O(1)
Similar Reads
Minimum replacements required to make given Matrix palindromic
Given a matrix with N rows and M columns, the task is to find the minimum replacements required to make all rows and columns of a given matrix palindromic. Examples: Input: a[][] = {{1, 2, 3}, {4, 5, 3}, {1, 2, 1}}Output: 2Explanation: To make the given matrix palindromic, replace a[0][2] by 1 and r
10 min read
Minimum changes required to make each path in a matrix palindrome
Given a matrix with N rows and M columns, the task is make all possible paths from the cell (N, M) to (1, 1) palindrome by minimum changes in the cell values. Possible moves from any cell (x, y) is either move Left(x - 1, y) or move Down (x, y - 1). Examples: Input: mat[ ][ ] = { { 1, 2, 2 }, { 1, 0
10 min read
Minimum Count of Bit flips required to make a Binary String Palindromic
Given an integer N, the task is to find the minimum number of bits required to be flipped to convert the binary representation of N into a palindrome. Examples: Input: N = 12 Output: 2 Explanation: Binary String representing 12 = "1100". To make "1100" a palindrome, convert the string to "0110". The
7 min read
Minimum decrements required to make all pairs of adjacent matrix elements distinct
Given a matrix mat[][] of dimension N * M, the task is to count the minimum number of decrements of distinct array elements required such that no two adjacent matrix elements are equal. Examples: Input: mat[][] = { {2, 3, 4}, {2, 5, 4} }Output: 3Explanation: Decrease the matrix elements arr[0][0], a
6 min read
Minimum increments required to make the sum of all adjacent matrix elements even
Given a matrix mat[][] of dimensions N Ã M, the task is to minimize the number of increments of matrix elements required to make the sum of adjacent matrix elements even.Note: For any matrix element mat[i][j], consider mat[i - 1][j], mat[i+1][j], mat[i][j - 1] and mat[i][j + 1] as its adjacent eleme
6 min read
Minimum Deletions to Make a String Palindrome
Given a string s of length n, the task is to remove or delete the minimum number of characters from the string so that the resultant string is a palindrome. Note: The order of characters should be maintained. Examples : Input : s = "aebcbda"Output : 2Explanation: Remove characters 'e' and 'd'. Resul
15+ min read
Minimum palindromic subarray removals to make array Empty
Given an array arr[] consisting of N elements, the task is to find the minimum palindromic subarray removals required to remove all elements from the array.Examples: Input: arr[] = {1, 3, 4, 1, 5}, N = 5 Output: 3 Explanation: Removal of 4 from the array leaves {1, 3, 1, 5}. Removal of {1, 3, 1} lea
6 min read
Count minimum swap to make string palindrome
Given a string S, the task is to find out the minimum no of adjacent swaps required to make string s palindrome. If it is not possible, then return -1. Examples: Input: aabcb Output: 3 Explanation: After 1st swap: abacb After 2nd swap: abcab After 3rd swap: abcba Input: adbcdbad Output: -1 ApproachT
6 min read
Minimum changes needed to make a 3*3 matrix magic square
Given a 3*3 matrix, find the minimum number of changes that need to be made to it in order to turn it into a magic square. A magic square is a square matrix whose sum of all the rows are the same, the sum of all the columns are the same and the sum of both the diagonals are the same. Examples: Input
9 min read
Minimum insertions to form a palindrome
Given a string s, the task is to find the minimum number of characters to be inserted to convert it to a palindrome.Examples:Input: s = "geeks"Output: 3Explanation: "skgeegks" is a palindromic string, which requires 3 insertions.Input: s= "abcd"Output: 3Explanation: "abcdcba" is a palindromic string
15+ min read