Maximum neighbor element in a matrix within distance K | Java 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 ; Utility function ; 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
import java . util . * ; class GFG { static void printMatrix ( int [ ] [ ] A ) { for ( int i = 0 ; i < A . length ; i ++ ) { for ( int j = 0 ; j < A [ 0 ] . length ; j ++ ) System . out . print ( A [ i ] [ j ] + " ▁ " ) ; System . out . print ( 'NEW_LINE'); } } static void copyMatrix ( int [ ] [ ] A , int [ ] [ ] B ) { int row = B . length ; int col = B [ 0 ] . length ; for ( int i = 0 ; i < row ; i ++ ) { for ( int j = 0 ; j < col ; j ++ ) { A [ i ] [ j ] = B [ i ] [ j ] ; } } } static int [ ] [ ] getMaxNeighbour ( int [ ] [ ] A , int K ) { int [ ] [ ] ans = new int [ A . length ] [ A [ 0 ] . length ] ; copyMatrix ( ans , A ) ; for ( int q = 1 ; q <= K ; q ++ ) { for ( int i = 0 ; i < A . length ; i ++ ) { for ( int j = 0 ; j < A [ 0 ] . length ; 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 . length - 1 ) maxi = Math . max ( maxi , ans [ i + 1 ] [ j ] ) ; if ( j < A [ 0 ] . length - 1 ) maxi = Math . max ( maxi , ans [ i ] [ j + 1 ] ) ; A [ i ] [ j ] = maxi ; } } copyMatrix ( 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 ) ) ; } }