Maximum neighbor element in a matrix within distance K | C # implementation to find the maximum neighbor element within the distance of less than K ; Function to print the matrix ; Loop to iterate over the matrix ; Function to find the maximum neighbor within the distance of less than equal to K ; Loop to find the maximum element within the distance of less than K ; Driver Code
using System ; class GFG { static void printMatrix ( int [ , ] A ) { for ( int i = 0 ; i < A . GetLength ( 0 ) ; i ++ ) { for ( int j = 0 ; j < A . GetLength ( 1 ) ; j ++ ) Console . Write ( A [ i , j ] + " ▁ " ) ; Console . Write ( ' STRNEWLINE ' ) ; } } static int [ , ] getMaxNeighbour ( int [ , ] A , int K ) { int [ , ] ans = A ; 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 ; } public static void Main ( String [ ] args ) { int [ , ] B = { { 1 , 2 , 3 } , { 4 , 5 , 6 } , { 7 , 8 , 9 } } ; printMatrix ( getMaxNeighbour ( B , 2 ) ) ; } }