Count ways to remove pairs from a matrix such that remaining elements can be grouped in vertical or horizontal pairs | Function to count ways to remove pairs such that the remaining elements can be arranged in pairs vertically or horizontally ; Store the size of matrix ; If N is odd , then no such pair exists ; Store the number of required pairs ; Initialize an auxiliary matrix and fill it with 0 s ; Traverse the matrix v [ ] [ ] ; Check if i + j is odd or even ; Increment the value dp [ v [ i ] [ j ] - 1 ] [ 0 ] by 1 ; Increment the value dp [ v [ i ] [ j ] - 1 ] [ 1 ] by 1 ; Iterate in range [ 0 , k - 1 ] using i ; Iterate in range [ i + 1 , k - 1 ] using j ; Update the ans ; Print the answer ; Driver code
def numberofpairs ( v , k ) : NEW_LINE INDENT n = len ( v ) NEW_LINE if ( n % 2 == 1 ) : NEW_LINE INDENT print ( 0 ) NEW_LINE return NEW_LINE DEDENT ans = 0 NEW_LINE dp = [ [ 0 for i in range ( 2 ) ] for j in range ( k ) ] NEW_LINE for i in range ( k ) : NEW_LINE INDENT for j in range ( 2 ) : NEW_LINE INDENT dp [ i ] [ j ] = 0 NEW_LINE DEDENT DEDENT for i in range ( n ) : NEW_LINE INDENT for j in range ( n ) : NEW_LINE INDENT if ( ( i + j ) % 2 == 0 ) : NEW_LINE INDENT dp [ v [ i ] [ j ] - 1 ] [ 0 ] += 1 NEW_LINE DEDENT else : NEW_LINE INDENT dp [ v [ i ] [ j ] - 1 ] [ 1 ] += 1 NEW_LINE DEDENT DEDENT DEDENT for i in range ( k ) : NEW_LINE INDENT for j in range ( i + 1 , k ) : NEW_LINE INDENT ans += dp [ i ] [ 0 ] * dp [ j ] [ 1 ] NEW_LINE ans += dp [ i ] [ 1 ] * dp [ j ] [ 0 ] NEW_LINE DEDENT DEDENT print ( ans ) NEW_LINE DEDENT mat = [ [ 1 , 2 ] , [ 3 , 4 ] ] NEW_LINE K = 4 NEW_LINE numberofpairs ( mat , K ) NEW_LINE