Maximum neighbor element in a matrix within distance K

Given a matrix mat[][] and an integer K, the task is to find the maximum neighbor within an absolute distance of K for each element of the matrix.
In other words for each Matrix[i][j] find maximum Matrix[p][q] such that abs (i-p) + abs (j-q) ? K.
Examples:Â
Â
Input: mat[][] = {{1, 2}, {4, 5}}, K = 1Â
Output: {{4, 5}, {5, 5}}Â
Explanation:Â
Maximum neighbour to the element mat[0][0] = 4 (Distance = 1)Â
Maximum neighbour to the element mat[0][1] = 5 (Distance = 1)Â
Maximum neighbour to the element mat[1][0] = 5 (Distance = 1)Â
Maximum neighbour to the element mat[1][1] = 5 (Distance = 0)
Input: mat[][] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}, K = 2Â
Output: {{7, 8, 9}, {8, 9, 9}, {9, 9, 9}}Â
Â
Â
Approach: The idea is to iterate over a loop from 1 to K, to choose the element from neighbors with distance less than or equal to K. Each time, Iterate over the matrix to find the maximum adjacent element for each element of the matrix.Â
Below is the implementation of the above approach:
Â
C++
// C++ implementation to find the // maximum neighbor element within// the distance of less than KÂ
#include <bits/stdc++.h>Â
using namespace std;Â
// Function to print the matrixvoid printMatrix(vector<vector<int> > A){    // Loop to iterate over the matrix    for (int i = 0; i < A.size(); i++) {        for (int j = 0; j < A[0].size(); j++)            cout << A[i][j] << ' ';        cout << '\n';    }}Â
// Function to find the maximum// neighbor within the distance// of less than equal to Kvector<vector<int> > getMaxNeighbour(        vector<vector<int> >& A, int K){    vector<vector<int> > ans = A;         // 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;}Â
// Driver Codeint main(){Â Â Â Â vector<vector<int> > B = { { 1, 2, 3 }, Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â { 4, 5, 6 }, { 7, 8, 9 } };Â Â Â Â printMatrix(getMaxNeighbour(B, 2));Â Â Â Â return 0;} |
Java
// Java implementation to find the// maximum neighbor element within// the distance of less than Kimport java.util.*;Â
class GFG {Â
    // Function to print the matrix    static void printMatrix(int[][] A)    {Â
        // Loop to iterate over the matrix        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('\n');        }    }Â
    // Function to copy content of one matrix into another    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];            }        }    }Â
    // Function to find the maximum    // neighbor within the distance    // of less than equal to K    static int[][] getMaxNeighbour(int[][] A, int K)    {        int[][] ans = new int[A.length][A[0].length];        copyMatrix(ans, A);Â
        // 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.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;    }Â
    // Driver Code    public static void main(String[] args)    {        int[][] B            = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };Â
        printMatrix(getMaxNeighbour(B, 2));    }}Â
// This code is contributed by Princi Singh |
Python3
# Python3 implementation to find the # maximum neighbor element within# the distance of less than KÂ Â # Function to print the matrixdef printMatrix(A):Â
    # Loop to iterate over the matrix    for i in range(len(A)):        for j in range(len(A[0])):            print(A[i][j], end = ' ')        print()          # Function to find the maximum# neighbor within the distance# of less than equal to Kdef getMaxNeighbour( A, K ):Â
    ans = A;          # Loop to find the maximum    # element within the distance    # of less than K    for q in range(1, K + 1):        for i in range(len(A)):            for j in range(len(A[0])):                                 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 < len(A) - 1):                    maxi = max(maxi, ans[i + 1][j]);                                     if (j < len(A[0]) - 1):                    maxi = max(maxi, ans[i][j + 1]);                                     A[i][j] = maxi;Â
        ans = A;         return ans;  # Driver Codeif __name__=='__main__':Â
    B = [ [ 1, 2, 3 ], [ 4, 5, 6 ], [ 7, 8, 9 ] ]    printMatrix(getMaxNeighbour(B, 2));     # This code is contributed by ruttvik_56 |
C#
// C# implementation to find the // maximum neighbor element within// the distance of less than Kusing System;Â
class GFG{Â
// Function to print the matrixstatic void printMatrix(int [,] A){         // Loop to iterate over the matrix    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('\n');    }}Â
// Function to find the maximum// neighbor within the distance// of less than equal to Kstatic int [,] getMaxNeighbour(int [,] A,                               int K){    int [,] ans = A;         // 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;}Â
// Driver Codepublic static void Main(String[] args){    int [,] B = { { 1, 2, 3 },                   { 4, 5, 6 },                  { 7, 8, 9 } };                         printMatrix(getMaxNeighbour(B, 2));}}Â
// This code is contributed by Princi Singh |
Javascript
<script>Â
// JavaScript implementation to find the // maximum neighbor element within// the distance of less than KÂ
// Function to print the matrixfunction printMatrix(A){    // Loop to iterate over the matrix    for (let i = 0; i < A.length; i++) {        for (let j = 0; j < A[0].length; j++)            document.write(A[i][j],' ');        document.write('</br>');    }}Â
// Function to find the maximum// neighbor within the distance// of less than equal to Kfunction getMaxNeighbour(A,K){    let ans = A;         // Loop to find the maximum    // element within the distance    // of less than K    for (let q = 1; q <= K; q++) {        for (let i = 0; i < A.length; i++) {            for (let j = 0; j < A[0].length; j++) {                let 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;            }        }        ans = A;    }    return ans;}Â
// Driver CodeÂ
let B = [ [ 1, 2, 3 ], [ 4, 5, 6 ], [ 7, 8, 9 ] ];printMatrix(getMaxNeighbour(B, 2));Â
// This code is contributed by shinjanpatra.<script> |
7 8 9 8 9 9 9 9 9
Â
Time Complexity: O(M*N*K)Â
Space Complexity: O(M*N)
Â
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 zambiatek!



