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
#include <bits/stdc++.h> NEW_LINE using namespace std ; void printMatrix ( vector < vector < int > > A ) { for ( int i = 0 ; i < A . size ( ) ; i ++ ) { for ( int j = 0 ; j < A [ 0 ] . size ( ) ; j ++ ) cout << A [ i ] [ j ] << ' ▁ ' ; cout << ' ' ; } } vector < vector < int > > getMaxNeighbour ( vector < vector < int > > & A , int K ) { vector < vector < int > > ans = A ; 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 ; } int main ( ) { vector < vector < int > > B = { { 1 , 2 , 3 } , { 4 , 5 , 6 } , { 7 , 8 , 9 } } ; printMatrix ( getMaxNeighbour ( B , 2 ) ) ; return 0 ; }