Loop to find the maximum element within the distance of less than K
for ( int q = 1 ; q <= K ; q ++ ) { for ( int i = 0 ; i < A . size ( ) ; i ++ ) { for ( int j = 0 ; j < A [ 0 ] . size ( ) ; j ++ ) { int maxi = ans [ i ] [ j ] ; if ( i > 0 ) maxi = max ( maxi , ans [ i - 1 ] [ j ] ) ; if ( j > 0 ) maxi = max ( maxi , ans [ i ] [ j - 1 ] ) ; if ( i < A . size ( ) - 1 ) maxi = max ( maxi , ans [ i + 1 ] [ j ] ) ; if ( j < A [ 0 ] . size ( ) - 1 ) maxi = max ( maxi , ans [ i ] [ j + 1 ] ) ; A [ i ] [ j ] = maxi ; } } ans = A ; } return ans ; }