Find number of transformation to make two Matrix Equal in C++

In this problem, we are given two matrices mat1[][] and mat2[][] of the same size. Our task is to find the number of transformations to make two Matrices Equal.

The transformation one matrices are −

  • Select any matrix of the two matrices.

  • Select a row or column from the matrices

  • Add 1 to all elements of the selected row or column.

Let’s take an example to understand the problem,

Input

mat1[][] = {{1 2}
{2 1}}
mat1[][] = {{2 3}
{4 3}}

Output

3

Explanation

1 2 => 2 2 => 2 3 => 2 3
2 1 => 3 1 => 3 2 => 4 3

Solution Approach

A simple solution to the problem is by finding whether transformation is possible or not. For this, we need to check −

if( mat[i][j] - mat[i][0] - mat[0][j] + mat[0][0] != 0 )

Then no solution exists.

Now, if transformation is possible, we will count transformations for rows and columns.

Program to illustrate the working of our solution,

Example

#include<iostream>
using namespace std;
int countEvenSumSubArray(int arr[], int n){
   int temp[2] = {1, 0};
   int count = 0, sum = 0;
   for (int i=0; i<=n-1; i++){
      sum = ( (sum + arr[i]) % 2 + 2) % 2;
      temp[sum]++;
   }
   count += (temp[0]*(temp[0]-1)/2);
   count += (temp[1]*(temp[1]-1)/2);
   return (count);
}
int main(){
   int arr[] = {2, 1, 4, 2};
   int n = sizeof (arr) / sizeof (arr[0]);
   cout<<"The count of Subarrays with even sum is "<<countEvenSumSubArray(arr, n);
   return (0);
}

Output

The count of Subarrays with even sum is 4
Updated on: 2026-03-11T22:50:56+05:30

312 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements