Add mat from i to j and vice versa , if possible . Since length of each contact field is at max some constant . ( say 30 ) so body execution of this for loop takes constant time .
for ( int j = i + 1 ; j < n ; j ++ ) if ( arr [ i ] . field1 == arr [ j ] . field1 arr [ i ] . field1 == arr [ j ] . field2 arr [ i ] . field1 == arr [ j ] . field3 arr [ i ] . field2 == arr [ j ] . field1 arr [ i ] . field2 == arr [ j ] . field2 arr [ i ] . field2 == arr [ j ] . field3 arr [ i ] . field3 == arr [ j ] . field1 arr [ i ] . field3 == arr [ j ] . field2 arr [ i ] . field3 == arr [ j ] . field3 ) { mat [ i ] [ j ] = 1 ; mat [ j ] [ i ] = 1 ; break ; } } }