Minimum operations to convert Binary Matrix A to B by flipping submatrix of size K | Function to count the operations required to convert matrix A to B ; Store the sizes of matrix ; Stores count of flips required ; Traverse the iven matrix ; Check if the matrix values are not equal ; Increment the count of moves ; Check if the current square sized exists or not ; Flip all the bits in this square sized submatrix ; Count of operations required ; Driver Code
def minMoves ( a , b , K ) : NEW_LINE INDENT n = len ( a ) NEW_LINE m = len ( a [ 0 ] ) NEW_LINE cntOperations = 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 cntOperations += 1 NEW_LINE if ( i + K - 1 >= n or j + K - 1 >= m ) : NEW_LINE INDENT return - 1 NEW_LINE DEDENT for p in range ( 0 , K ) : NEW_LINE INDENT for q in range ( 0 , K ) : NEW_LINE INDENT if ( a [ i + p ] [ j + q ] == '0' ) : NEW_LINE INDENT a [ i + p ] [ j + q ] = '1' NEW_LINE DEDENT else : NEW_LINE INDENT a [ i + p ] [ j + q ] = '0' NEW_LINE DEDENT DEDENT DEDENT DEDENT DEDENT DEDENT return cntOperations NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT A = [ [ '1' , '0' , '0' ] , [ '0' , '0' , '0' ] , [ '0' , '0' , '0' ] ] NEW_LINE B = [ [ '0' , '0' , '0' ] , [ '0' , '0' , '0' ] , [ '0' , '0' , '0' ] ] NEW_LINE K = 3 NEW_LINE print ( minMoves ( A , B , K ) ) NEW_LINE DEDENT