Minimum swaps needed to convert given Binary Matrix A to Binary Matrix B | Function to count the minimum number of swaps required to convert matrix A to matrix B ; Stores number of cells such that matrix A contains 0 and matrix B contains 1 ; Stores number of cells such that matrix A contains 1 and matrix B contains 0 ; Iterate over the range [ 0 , N - 1 ] ; Iterate over the range [ 0 , M - 1 ] ; If A [ i ] [ j ] = 1 and B [ i ] [ j ] = 0 ; If A [ i ] [ j ] = 0 and B [ i ] [ j ] = 1 ; If count01 is equal to count10 ; Otherwise , ; Driver Code
def minSwaps ( N , M , A , B ) : NEW_LINE INDENT count01 = 0 NEW_LINE count10 = 0 NEW_LINE for i in range ( 0 , N ) : NEW_LINE INDENT for j in range ( 0 , M ) : NEW_LINE INDENT if ( A [ i ] [ j ] != B [ i ] [ j ] ) : NEW_LINE INDENT if ( A [ i ] [ j ] == 1 ) : NEW_LINE INDENT count10 += 1 NEW_LINE DEDENT else : NEW_LINE INDENT count01 += 1 NEW_LINE DEDENT DEDENT DEDENT DEDENT if ( count01 == count10 ) : NEW_LINE INDENT return count01 NEW_LINE DEDENT else : NEW_LINE INDENT return - 1 NEW_LINE DEDENT DEDENT A = [ [ 1 , 1 , 0 ] , [ 0 , 0 , 1 ] , [ 0 , 1 , 0 ] ] NEW_LINE B = [ [ 0 , 0 , 1 ] , [ 0 , 1 , 0 ] , [ 1 , 1 , 0 ] ] NEW_LINE N = len ( A ) NEW_LINE M = len ( B [ 0 ] ) NEW_LINE print ( minSwaps ( N , M , A , B ) ) NEW_LINE