Check if a pair with given absolute difference exists in a Matrix | CPP code to check for pair with given difference exists in the matrix or not ; Function to check if a pair with given difference exists in the matrix ; Store elements in a hash ; Loop to iterate over the elements of the matrix ; Driver Code ; Input matrix ; Given difference
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define N  4 NEW_LINE #define M  4 NEW_LINE bool isPairWithDiff ( int mat [ N ] [ M ] , int k ) { unordered_set < int > ump ; for ( int i = 0 ; i < N ; i ++ ) { for ( int j = 0 ; j < M ; j ++ ) { if ( mat [ i ] [ j ] > k ) { int m = mat [ i ] [ j ] - k ; if ( ump . find ( m ) != ump . end ( ) ) { return true ; } } else { int m = k - mat [ i ] [ j ] ; if ( ump . find ( m ) != ump . end ( ) ) { return true ; } } ump . insert ( mat [ i ] [ j ] ) ; } } return false ; } int main ( ) { int mat [ N ] [ M ] = { { 5 , 2 , 3 , 4 } , { 5 , 6 , 7 , 8 } , { 9 , 10 , 11 , 12 } , { 13 , 14 , 15 , 100 } } ; int k = 85 ; if ( isPairWithDiff ( mat , k ) ) cout << " YES " << endl ; else cout << " NO " << endl ; return 0 ; }