Skip to content
Related Articles

Related Articles

Find all adjacent elements of given element in a 2D Array or Matrix

View Discussion
Improve Article
Save Article
  • Difficulty Level : Hard
  • Last Updated : 08 Aug, 2022
View Discussion
Improve Article
Save Article

Given a two-dimensional integer array arr[ ][ ], return all the adjacent elements of a particular integer whose position is given as (x, y).

Adjacent elements are all the elements that share a common side or point i.e., they have a vertical, horizontal or diagonal distance of 1.

An example of a 2D array

An example of a 2D array

Examples:

Input: arr[][] = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} }, x = 1, y = 1
Output: {1, 2, 3, 4, 6, 7, 8, 9}
Explanation: Elements adjacent to arr[1][1] (i.e., 5) are: 
arr[0][0], arr[0][1], arr[0][2], arr[1][0], arr[1][2], arr[2][0], arr[2][1], and arr[2][2].

Input: arr[][] = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} }, x = 0, y = 2
Output: {2, 5, 6}

 

Method 1: In this approach, we have to check for all the possible adjacent positions and print them as the adjacent elements of the given elements.
The only problem in this approach is that a possible adjacent position may not be a valid position of the matrix, i.e., the index may be out of bound for the 2-dimensional array. So we have to keep checking for every adjacent position if that is a valid position or not.

Below is the implementation of the above approach.

C++




// C++ code to implement the approach
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to check whether
// position is valid or not
bool isValidPos(int i, int j, int n, int m)
{
    if (i < 0 || j < 0 || i > n - 1 || j > m - 1)
        return 0;
    return 1;
}
 
// Function that returns all adjacent elements
vector<int> getAdjacent(vector<vector<int> >& arr, int i,
                        int j)
{
    // Size of given 2d array
    int n = arr.size();
    int m = arr[0].size();
 
    // Initialising a vector array
    // where adjacent element will be stored
    vector<int> v;
 
    // Checking for all the possible adjacent positions
    if (isValidPos(i - 1, j - 1, n, m))
        v.push_back(arr[i - 1][j - 1]);
    if (isValidPos(i - 1, j, n, m))
        v.push_back(arr[i - 1][j]);
    if (isValidPos(i - 1, j + 1, n, m))
        v.push_back(arr[i - 1][j + 1]);
    if (isValidPos(i, j - 1, n, m))
        v.push_back(arr[i][j - 1]);
    if (isValidPos(i, j + 1, n, m))
        v.push_back(arr[i][j + 1]);
    if (isValidPos(i + 1, j - 1, n, m))
        v.push_back(arr[i + 1][j - 1]);
    if (isValidPos(i + 1, j, n, m))
        v.push_back(arr[i + 1][j]);
    if (isValidPos(i + 1, j + 1, n, m))
        v.push_back(arr[i + 1][j + 1]);
 
    // Returning the vector
    return v;
}
 
// Driver Code
int main()
{
    // Given vector array
    vector<vector<int> > arr{ { 1, 2, 3 },
                              { 4, 5, 6 },
                              { 7, 8, 9 } };
    int x = 1, y = 1;
 
    // Function call
    vector<int> ans = getAdjacent(arr, x, y);
 
    // Print all the adjacent elements
    for (int i = 0; i < ans.size(); i++) {
        cout << ans[i] << " ";
    }
    return 0;
}


Java




// Java code to implement the approach
 
import java.io.*;
import java.util.*;
 
class GFG {
 
    // Function to check whether position is valid or not
    static boolean isValidPos(int i, int j, int n, int m)
    {
        if (i < 0 || j < 0 || i > n - 1 || j > m - 1) {
            return false;
        }
        return true;
    }
 
    // Function that returns all adjacent elements
    static List<Integer>
    getAdjacent(List<List<Integer> > arr, int i, int j)
    {
        // Size of given 2d array
        int n = arr.size();
        int m = arr.get(0).size();
 
        // Initialising a array list where adjacent element
        // will be stored
        List<Integer> v = new ArrayList<>();
 
        // Checking for all the possible adjacent positions
        if (isValidPos(i - 1, j - 1, n, m)) {
            v.add(arr.get(i - 1).get(j - 1));
        }
        if (isValidPos(i - 1, j, n, m)) {
            v.add(arr.get(i - 1).get(j));
        }
        if (isValidPos(i - 1, j + 1, n, m)) {
            v.add(arr.get(i - 1).get(j + 1));
        }
        if (isValidPos(i, j - 1, n, m)) {
            v.add(arr.get(i).get(j - 1));
        }
        if (isValidPos(i, j + 1, n, m)) {
            v.add(arr.get(i).get(j + 1));
        }
        if (isValidPos(i + 1, j - 1, n, m)) {
            v.add(arr.get(i + 1).get(j - 1));
        }
        if (isValidPos(i + 1, j, n, m)) {
            v.add(arr.get(i + 1).get(j));
        }
        if (isValidPos(i + 1, j + 1, n, m)) {
            v.add(arr.get(i + 1).get(j + 1));
        }
 
        // Returning the arraylist
        return v;
    }
 
    public static void main(String[] args)
    {
 
        List<List<Integer> > arr = new ArrayList<>();
 
        arr.add(
            new ArrayList<Integer>(Arrays.asList(1, 2, 3)));
        arr.add(
            new ArrayList<Integer>(Arrays.asList(4, 5, 6)));
        arr.add(
            new ArrayList<Integer>(Arrays.asList(7, 8, 9)));
 
        int x = 1, y = 1;
 
        // Function call
        List<Integer> ans = getAdjacent(arr, x, y);
 
        // Print all the adjacent elements
        for (int i = 0; i < ans.size(); i++) {
            System.out.print(ans.get(i) + " ");
        }
    }
}
 
// This code is contributed by lokeshmvs21.


Python3




# python code to implement the approach
 
# Function to check whether
# position is valid or not
 
 
def isValidPos(i, j, n, m):
 
    if (i < 0 or j < 0 or i > n - 1 or j > m - 1):
        return 0
    return 1
 
 
# Function that returns all adjacent elements
def getAdjacent(arr, i, j):
 
    # Size of given 2d array
    n = len(arr)
    m = len(arr[0])
 
    # Initialising a vector array
    # where adjacent element will be stored
    v = []
 
    # Checking for all the possible adjacent positions
    if (isValidPos(i - 1, j - 1, n, m)):
        v.append(arr[i - 1][j - 1])
    if (isValidPos(i - 1, j, n, m)):
        v.append(arr[i - 1][j])
    if (isValidPos(i - 1, j + 1, n, m)):
        v.append(arr[i - 1][j + 1])
    if (isValidPos(i, j - 1, n, m)):
        v.append(arr[i][j - 1])
    if (isValidPos(i, j + 1, n, m)):
        v.append(arr[i][j + 1])
    if (isValidPos(i + 1, j - 1, n, m)):
        v.append(arr[i + 1][j - 1])
    if (isValidPos(i + 1, j, n, m)):
        v.append(arr[i + 1][j])
    if (isValidPos(i + 1, j + 1, n, m)):
        v.append(arr[i + 1][j + 1])
 
    # Returning the vector
    return v
 
 
# Driver Code
if __name__ == "__main__":
 
    # Given vector array
    arr = [[1, 2, 3],
           [4, 5, 6],
           [7, 8, 9]]
    x, y = 1, 1
 
    # Function call
    ans = getAdjacent(arr, x, y)
 
    # Print all the adjacent elements
    for i in range(0, len(ans)):
        print(ans[i], end=" ")
 
    # This code is contributed by rakeshsahni


C#




using System;
using System.Collections.Generic;
 
public class GFG{
 
  // Function to check whether
  // position is valid or not
  public static bool isValidPos(int i, int j, int n, int m)
  {
    if (i < 0 || j < 0 || i > n - 1 || j > m - 1)
      return false;
    return true;
   
  // Function that returns all adjacent elements
  public static List<int> getAdjacent(int[][] arr, int i,
                                      int j)
  {
    // Size of given 2d array
    int n = arr.Length;
    int m = arr[0].Length;
 
    // Initialising a list
    // where adjacent element will be stored
 
    List<int> v = new List<int>();
 
    // Checking for all the possible adjacent positions
    if (isValidPos(i - 1, j - 1, n, m))
    { v.Add(arr[i - 1][j - 1]);}
    if (isValidPos(i - 1, j, n, m))
    {  v.Add(arr[i - 1][j]);}
    if (isValidPos(i - 1, j + 1, n, m))
    { v.Add(arr[i - 1][j + 1]);}
    if (isValidPos(i, j - 1, n, m))
    {  v.Add(arr[i][j - 1]);}
    if (isValidPos(i, j + 1, n, m))
    { v.Add(arr[i][j + 1]);}
    if (isValidPos(i + 1, j - 1, n, m))
    { v.Add(arr[i + 1][j - 1]);}
    if (isValidPos(i + 1, j, n, m))
    { v.Add(arr[i + 1][j]);}
    if (isValidPos(i + 1, j + 1, n, m))
    {  v.Add(arr[i + 1][j + 1]);}
 
    // Returning the list
    return v;
  }
 
  static public void Main (){
 
    // Given array
    int[][] arr = new int[3][]{ new int[]{ 1, 2, 3 },
                               new int[] { 4, 5, 6 },
                               new int[] { 7, 8, 9 } };
 
 
    int x = 1, y = 1;
 
    // Function call
    List<int> ans = getAdjacent(arr, x, y);
 
    // Print all the adjacent elements
    for (int i = 0; i < ans.Count; i++) {
      System.Console.Write(ans[i]);
      System.Console.Write(" ");
    }
 
  }
}
 
// This code is contributed by akashish__


Javascript




<script>
       // JavaScript code for the above approach
 
       // Function to check whether
       // position is valid or not
       function isValidPos(i, j, n, m) {
           if (i < 0 || j < 0 || i > n - 1 || j > m - 1)
               return 0;
           return 1;
       }
 
       // Function that returns all adjacent elements
       function getAdjacent(arr, i, j) {
           // Size of given 2d array
           let n = arr.length;
           let m = arr[0].length;
 
           // Initialising a vector array
           // where adjacent element will be stored
           let v = [];
 
           // Checking for all the possible adjacent positions
           if (isValidPos(i - 1, j - 1, n, m))
               v.push(arr[i - 1][j - 1]);
           if (isValidPos(i - 1, j, n, m))
               v.push(arr[i - 1][j]);
           if (isValidPos(i - 1, j + 1, n, m))
               v.push(arr[i - 1][j + 1]);
           if (isValidPos(i, j - 1, n, m))
               v.push(arr[i][j - 1]);
           if (isValidPos(i, j + 1, n, m))
               v.push(arr[i][j + 1]);
           if (isValidPos(i + 1, j - 1, n, m))
               v.push(arr[i + 1][j - 1]);
           if (isValidPos(i + 1, j, n, m))
               v.push(arr[i + 1][j]);
           if (isValidPos(i + 1, j + 1, n, m))
               v.push(arr[i + 1][j + 1]);
 
           // Returning the vector
           return v;
       }
 
       // Driver Code
 
       // Given vector array
       let arr = [[1, 2, 3],
       [4, 5, 6],
       [7, 8, 9]];
       let x = 1, y = 1;
 
       // Function call
       let ans = getAdjacent(arr, x, y);
 
       // Print all the adjacent elements
       for (let i = 0; i < ans.length; i++) {
           document.write(ans[i] + " ");
       }
        
   // This code is contributed by Potta Lokesh
   </script>


Output

1 2 3 4 6 7 8 9 

Time Complexity: O(1)
Auxiliary Space: O(1)

Method 2: In this approach, we will not check for every adjacent element whether it is a valid position or not, we will directly code in a way that it will only print the valid elements.

  • We will iterate using two loops, where the outer loop denotes deviation in row number and the inner loop denotes deviation in column number. The deviation is in the range of -1 to 1 and gets adjusted based on the provided position.
  • Here is only one special case: if both the deviations are 0 then it denotes the same element.

Below is the implementation of the above approach.

C++




// C++ code to implement the approach
 
#include <bits/stdc++.h>
using namespace std;
 
// Function that returns all the adjacent elements
vector<int> getAdjacent(vector<vector<int> >& arr, int i,
                        int j)
{
    // Size of given 2d array
    int n = arr.size();
    int m = arr[0].size();
 
    // Initialising a vector array where
    // adjacent elements will be stored
    vector<int> v;
 
    // Checking for adjacent elements
    // and adding them to array
 
    // Deviation of row that gets adjusted
    // according to the provided position
    for (int dx = (i > 0 ? -1 : 0); dx <= (i < n ? 1 : 0);
         ++dx) {
 
        // Deviation of the column that
        // gets adjusted according to
        // the provided position
        for (int dy = (j > 0 ? -1 : 0);
             dy <= (j < m ? 1 : 0); ++dy) {
            if (dx != 0 || dy != 0) {
                v.push_back(arr[i + dx][j + dy]);
            }
        }
    }
 
    // Returning the vector array
    return v;
}
 
// Driver Code
int main()
{
    // Given vector array
    vector<vector<int> > arr{ { 1, 2, 3 },
                              { 4, 5, 6 },
                              { 7, 8, 9 } };
    int x = 1, y = 1;
 
    // Function call
    vector<int> ans = getAdjacent(arr, x, y);
 
    // Print all the adjacent elements
    for (int i = 0; i < ans.size(); i++) {
        cout << ans[i] << " ";
    }
    return 0;
}


Java




// Java code to implement the approach
import java.util.*;
 
public class GFG{
 
  // Function that returns all the adjacent elements
  public static ArrayList<Integer> getAdjacent(int[][] arr, int i,
                                               int j)
  {
 
    // Size of given 2d array
    int n = arr.length;
    int m = arr[0].length;
 
    // Initialising a vector array where
    // adjacent elements will be stored
    ArrayList<Integer> v = new ArrayList<Integer>();
 
    // Checking for adjacent elements
    // and adding them to array
 
    // Deviation of row that gets adjusted
    // according to the provided position
    for (int dx = (i > 0 ? -1 : 0); dx <= (i < n ? 1 : 0);
         ++dx) {
 
      // Deviation of the column that
      // gets adjusted according to
      // the provided position
      for (int dy = (j > 0 ? -1 : 0);
           dy <= (j < m ? 1 : 0); ++dy) {
        if (dx != 0 || dy != 0) {
          v.add(arr[i + dx][j + dy]);
        }
      }
    }
 
    // Returning the vector array
    return v;
  }
 
 
  public static void main (String[] args){
 
    // Given vector array
    int[][] arr = { { 1, 2, 3 },{ 4, 5, 6 },  { 7, 8, 9 } };
    int x = 1, y = 1;
 
    // Function call
    ArrayList<Integer> ans = getAdjacent(arr, x, y);
 
    // Print all the adjacent elements
    for (int i = 0; i < ans.size(); i++) {
      System.out.print(ans.get(i));
      System.out.print(" ");
 
    }
  }
}
 
// This code is contributed by phasing17


Python3




# Pyhton3 code to implement the approach
 
# Function that returns all the adjacent elements
def getAdjacent(arr, i, j):
   
    # Size of given 2d array
    n = len(arr)
    m = len(arr[0])
 
    # Initialising a vector array where
    # adjacent elements will be stored
    v = []
 
    # Checking for adjacent elements
    # and adding them to array
 
    # Deviation of row that gets adjusted
    # according to the provided position
    for dx in range (-1 if (i > 0) else 0 , 2 if (i < n) else 1):
 
        # Deviation of the column that
        # gets adjusted according to
        # the provided position
        for dy in range( -1 if (j > 0) else 0,2 if (j < m) else 1):
            if (dx is not 0 or dy is not 0):
                v.append(arr[i + dx][j + dy])
 
 
    #Returning the vector array
    return v
 
# Driver Code
#Given vector array
arr = [ [ 1, 2, 3 ],
        [ 4, 5, 6 ],
        [ 7, 8, 9 ] ];
x = 1
y = 1
 
# Function call
ans = getAdjacent(arr, x, y)
 
# Print all the adjacent elements
for i in range(0,len(ans)):
  print(ans[i],end= " ")
   
# This code is contributed by akashish__


C#




using System;
using System.Collections.Generic;
 
public class GFG{
 
  // Function that returns all the adjacent elements
  public static List<int> getAdjacent(int[][] arr, int i,
                                      int j)
  {
    // Size of given 2d array
    int n = arr.Length;
    int m = arr[0].Length;
 
    // Initialising a vector array where
    // adjacent elements will be stored
    List<int> v = new List<int>();
 
    // Checking for adjacent elements
    // and adding them to array
 
    // Deviation of row that gets adjusted
    // according to the provided position
    for (int dx = (i > 0 ? -1 : 0); dx <= (i < n ? 1 : 0);
         ++dx) {
 
      // Deviation of the column that
      // gets adjusted according to
      // the provided position
      for (int dy = (j > 0 ? -1 : 0);
           dy <= (j < m ? 1 : 0); ++dy) {
        if (dx != 0 || dy != 0) {
          v.Add(arr[i + dx][j + dy]);
        }
      }
    }
 
    // Returning the vector array
    return v;
  }
 
 
  static public void Main (){
 
    // Given vector array
    int[][] arr = new int[3][]{new int[] { 1, 2, 3 },
                               new int[] { 4, 5, 6 },
                               new int[] { 7, 8, 9 } };
    int x = 1, y = 1;
 
    // Function call
    List<int> ans = getAdjacent(arr, x, y);
 
    // Print all the adjacent elements
    for (int i = 0; i < ans.Count; i++) {
      System.Console.Write(ans[i]);
      System.Console.Write(" ");
 
    }
  }
}
 
// This code is contributed by akashish__


Javascript




// JavaScript code to implement the approach
 
// Function that returns all the adjacent elements
function getAdjacent(arr, i, j)
{
 
    // Size of given 2d array
    let n = arr.length;
    let m = arr[0].length;
 
    // Initialising a vector array where
    // adjacent elements will be stored
    let v = [];
 
    // Checking for adjacent elements
    // and adding them to array
 
    // Deviation of row that gets adjusted
    // according to the provided position
    for (var dx = (i > 0 ? -1 : 0); dx <= (i < n ? 1 : 0);
         ++dx) {
 
        // Deviation of the column that
        // gets adjusted according to
        // the provided position
        for (var dy = (j > 0 ? -1 : 0);
             dy <= (j < m ? 1 : 0); ++dy) {
            if (dx != 0 || dy != 0) {
                v.push(arr[i + dx][j + dy]);
            }
        }
    }
 
    // Returning the vector array
    return v;
}
 
// Driver Code
 
// Given vector array
let arr = [ [1, 2, 3 ], [ 4, 5, 6 ], [7, 8, 9 ]];
let x = 1, y = 1;
 
// Function call
let ans = getAdjacent(arr, x, y);
 
// Print all the adjacent elements
for (var i = 0; i < ans.length; i++)
    process.stdout.write(ans[i] + " ");
 
// This code is contributed by phasing17


Output

1 2 3 4 6 7 8 9 

Time complexity: O(1) 
Auxiliary Space: O(1)


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!