Minimum operations required to make each row and column of matrix equals | 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
def findMinOpeartion ( matrix , n ) : NEW_LINE INDENT sumRow = [ 0 ] * n NEW_LINE sumCol = [ 0 ] * n NEW_LINE for i in range ( n ) : NEW_LINE INDENT for j in range ( n ) : NEW_LINE INDENT sumRow [ i ] += matrix [ i ] [ j ] NEW_LINE sumCol [ j ] += matrix [ i ] [ j ] NEW_LINE DEDENT DEDENT maxSum = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT maxSum = max ( maxSum , sumRow [ i ] ) NEW_LINE maxSum = max ( maxSum , sumCol [ i ] ) NEW_LINE DEDENT count = 0 NEW_LINE i = 0 NEW_LINE j = 0 NEW_LINE while i < n and j < n : NEW_LINE INDENT diff = min ( maxSum - sumRow [ i ] , maxSum - sumCol [ j ] ) NEW_LINE matrix [ i ] [ j ] += diff NEW_LINE sumRow [ i ] += diff NEW_LINE sumCol [ j ] += diff NEW_LINE count += diff NEW_LINE if ( sumRow [ i ] == maxSum ) : NEW_LINE INDENT i += 1 NEW_LINE DEDENT if ( sumCol [ j ] == maxSum ) : NEW_LINE INDENT j += 1 NEW_LINE DEDENT DEDENT return count NEW_LINE DEDENT def printMatrix ( matrix , n ) : NEW_LINE INDENT for i in range ( n ) : NEW_LINE INDENT for j in range ( n ) : NEW_LINE INDENT print ( matrix [ i ] [ j ] , end = " ▁ " ) NEW_LINE DEDENT print ( ) NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT matrix = [ [ 1 , 2 ] , [ 3 , 4 ] ] NEW_LINE print ( findMinOpeartion ( matrix , 2 ) ) NEW_LINE printMatrix ( matrix , 2 ) NEW_LINE DEDENT