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 . GetLength ( 0 ) ; i ++ ) { for ( int j = 0 ; j < A . GetLength ( 1 ) ; j ++ ) { int maxi = ans [ i , j ] ; if ( i > 0 ) maxi = Math . Max ( maxi , ans [ i - 1 , j ] ) ; if ( j > 0 ) maxi = Math . Max ( maxi , ans [ i , j - 1 ] ) ; if ( i < A . GetLength ( 0 ) - 1 ) maxi = Math . Max ( maxi , ans [ i + 1 , j ] ) ; if ( j < A . GetLength ( 0 ) - 1 ) maxi = Math . Max ( maxi , ans [ i , j + 1 ] ) ; A [ i , j ] = maxi ; } } ans = A ; } return ans ; }