Check if a pair with given absolute difference exists in a Matrix | Python 3 program to check for pairs with given difference exits in the matrix or not ; Function to check if a pair with given difference exist in the matrix ; Store elements in a hash ; Loop to iterate over the elements of the matrix ; Input matrix ; given difference
N = 4 NEW_LINE M = 4 NEW_LINE def isPairWithDiff ( mat , k ) : NEW_LINE INDENT s = set ( ) NEW_LINE for i in range ( N ) : NEW_LINE INDENT for j in range ( M ) : NEW_LINE INDENT if mat [ i ] [ j ] > k : NEW_LINE INDENT m = mat [ i ] [ j ] - k NEW_LINE if m in s : NEW_LINE INDENT return True NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT m = k - mat [ i ] [ j ] NEW_LINE if m in s : NEW_LINE INDENT return True NEW_LINE DEDENT DEDENT s . add ( mat [ i ] [ j ] ) NEW_LINE DEDENT DEDENT return False NEW_LINE DEDENT n , m = 4 , 4 NEW_LINE mat = [ [ 5 , 2 , 3 , 4 ] , [ 5 , 6 , 7 , 8 ] , [ 9 , 10 , 11 , 12 ] , [ 13 , 14 , 15 , 100 ] ] NEW_LINE k = 85 NEW_LINE if isPairWithDiff ( mat , k ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT