Wednesday, 27 Oct 2021

# Minimum decrements required to make all pairs of adjacent matrix elements distinct

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, arr, and arr by 1 each. The matrix modifies to {{1, 2, 3}, {2, 5, 4}}. Therefore, all pairs of adjacent matrix elements becomes different.
Input: mat[][] = { {1, 2, 3}, {1, 2, 3}, {1, 2, 3} }Output: 3Explanation: Decrease each element present in the second row of the matrix by 1. The matrix will have all adjacent element different as shown below:1 2 30 1 21 2 3

Approach: The main idea is to solve the given problem by assuming the matrix like a Chess Grid shown below:
Follow the steps below to solve the problem:
Traverse the matrix
For every matrix element, following two cases arise:
Case 1 : If (i + j) is even, mat[i][j] should be even. Otherwise, mat[i][j] should be odd.
Case 2: If (i + j) is even, value at mat[i][j] should be even. Otherwise, value at mat[i][j] should be odd.

Therefore, calculate the number of operations required in both cases.
Print the minimum of the two counts obtained.
Below is the implementation of the above approach:

C++

#include
using namespace std;

const int n = 3;
const int m = 3;

void countDecrements(long long arr[][m])
{
int count_1 = 0;
int count_2 = 0;

for (int i = 0; i < n; i++) {         for (int j = 0; j < m; j++) {                             if ((i + j) % 2 == arr[i][j] % 2)                 count_1++;                             if (1 - (i + j) % 2 == arr[i][j] % 2)                 count_2++;         }     }                  cout