Minimum operations required to make each row and column of matrix equals | C ++ Program to Find minimum number of operation required such that sum of elements on each row and column becomes same ; Function to find minimum operation required to make sum of each row and column equals ; Initialize the sumRow [ ] and sumCol [ ] array to 0 ; Calculate sumRow [ ] and sumCol [ ] array ; Find maximum sum value in either row or in column ; Find minimum increment required in either row or column ; Add difference in corresponding cell , sumRow [ ] and sumCol [ ] array ; Update the count variable ; If ith row satisfied , increment ith value for next iteration ; If jth column satisfied , increment jth value for next iteration ; Utility function to print matrix ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int findMinOpeartion ( int matrix [ ] [ 2 ] , int n ) { int sumRow [ n ] , sumCol [ n ] ; memset ( sumRow , 0 , sizeof ( sumRow ) ) ; memset ( sumCol , 0 , sizeof ( sumCol ) ) ; for ( int i = 0 ; i < n ; ++ i ) for ( int j = 0 ; j < n ; ++ j ) { sumRow [ i ] += matrix [ i ] [ j ] ; sumCol [ j ] += matrix [ i ] [ j ] ; } int maxSum = 0 ; for ( int i = 0 ; i < n ; ++ i ) { maxSum = max ( maxSum , sumRow [ i ] ) ; maxSum = max ( maxSum , sumCol [ i ] ) ; } int count = 0 ; for ( int i = 0 , j = 0 ; i < n && j < n ; ) { int diff = min ( maxSum - sumRow [ i ] , maxSum - sumCol [ j ] ) ; matrix [ i ] [ j ] += diff ; sumRow [ i ] += diff ; sumCol [ j ] += diff ; count += diff ; if ( sumRow [ i ] == maxSum ) ++ i ; if ( sumCol [ j ] == maxSum ) ++ j ; } return count ; } void printMatrix ( int matrix [ ] [ 2 ] , int n ) { for ( int i = 0 ; i < n ; ++ i ) { for ( int j = 0 ; j < n ; ++ j ) cout << matrix [ i ] [ j ] << " ▁ " ; cout << " STRNEWLINE " ; } } int main ( ) { int matrix [ ] [ 2 ] = { { 1 , 2 } , { 3 , 4 } } ; cout << findMinOpeartion ( matrix , 2 ) << " STRNEWLINE " ; printMatrix ( matrix , 2 ) ; return 0 ; }