Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Questions on Array
  • Practice Array
  • MCQs on Array
  • Tutorial on Array
  • Types of Arrays
  • Array Operations
  • Subarrays, Subsequences, Subsets
  • Reverse Array
  • Static Vs Arrays
  • Array Vs Linked List
  • Array | Range Queries
  • Advantages & Disadvantages
Open In App
Next Article:
XOR of major diagonal elements of a 3D Matrix
Next article icon

All adjacent of a given element in a 2D Array or Matrix

Last Updated : 24 Mar, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Given a 2d integer array arr, your task is to return all the adjacent elements of a particular integer whose position is given as (x, y).
Note: 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}

By Checking All Adjacent Cells Separately - O(1) Time and O(1) Space

The idea is to create 8 if conditions to check for all 8 neighbors of given cell (x, y), and include the valid cells in the answer.

C++
#include <bits/stdc++.h> using namespace std;  // Function to check whether // position is valid or not int isValidPos(int i, int j, int n, int m) {     if (i < 0 || j < 0 || i >= n || j >= m)         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> ans;      // Checking for all the possible adjacent positions     if (isValidPos(i - 1, j - 1, n, m))         ans.push_back(arr[i - 1][j - 1]);     if (isValidPos(i - 1, j, n, m))         ans.push_back(arr[i - 1][j]);     if (isValidPos(i - 1, j + 1, n, m))         ans.push_back(arr[i - 1][j + 1]);     if (isValidPos(i, j - 1, n, m))         ans.push_back(arr[i][j - 1]);     if (isValidPos(i, j + 1, n, m))         ans.push_back(arr[i][j + 1]);     if (isValidPos(i + 1, j - 1, n, m))         ans.push_back(arr[i + 1][j - 1]);     if (isValidPos(i + 1, j, n, m))         ans.push_back(arr[i + 1][j]);     if (isValidPos(i + 1, j + 1, n, m))         ans.push_back(arr[i + 1][j + 1]);      // Returning the vector     return ans; }  int main() {     vector<vector<int>> arr =      {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};     int x = 1, y = 1;     vector<int> ans = getAdjacent(arr, x, y);     for (int i = 0; i < ans.size(); i++) {         cout << ans[i] << " ";     }     return 0; } 
Java
import java.util.*;  class GfG {      // Function to check whether     // position is valid or not     static int isValidPos(int i, int j, int n, int m) {         if (i < 0 || j < 0 || i >= n || j >= m)             return 0;         return 1;     }      // Function that returns all adjacent elements     static List<Integer> 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 elements will be stored         List<Integer> ans = new ArrayList<>();          // Checking for all the possible adjacent positions         if (isValidPos(i - 1, j - 1, n, m) == 1)             ans.add(arr[i - 1][j - 1]);         if (isValidPos(i - 1, j, n, m) == 1)             ans.add(arr[i - 1][j]);         if (isValidPos(i - 1, j + 1, n, m) == 1)             ans.add(arr[i - 1][j + 1]);         if (isValidPos(i, j - 1, n, m) == 1)             ans.add(arr[i][j - 1]);         if (isValidPos(i, j + 1, n, m) == 1)             ans.add(arr[i][j + 1]);         if (isValidPos(i + 1, j - 1, n, m) == 1)             ans.add(arr[i + 1][j - 1]);         if (isValidPos(i + 1, j, n, m) == 1)             ans.add(arr[i + 1][j]);         if (isValidPos(i + 1, j + 1, n, m) == 1)             ans.add(arr[i + 1][j + 1]);          // Returning the list         return ans;     }      public static void main(String[] args) {         int[][] arr = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};         int x = 1, y = 1;         List<Integer> ans = getAdjacent(arr, x, y);         for (int num : ans) {             System.out.print(num + " ");         }     } } 
Python
# Function to check whether # position is valid or not def isValidPos(i, j, n, m):     if i < 0 or j < 0 or i >= n or j >= m:         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 list where adjacent elements will be stored     ans = []      # Checking for all the possible adjacent positions     if isValidPos(i - 1, j - 1, n, m):         ans.append(arr[i - 1][j - 1])     if isValidPos(i - 1, j, n, m):         ans.append(arr[i - 1][j])     if isValidPos(i - 1, j + 1, n, m):         ans.append(arr[i - 1][j + 1])     if isValidPos(i, j - 1, n, m):         ans.append(arr[i][j - 1])     if isValidPos(i, j + 1, n, m):         ans.append(arr[i][j + 1])     if isValidPos(i + 1, j - 1, n, m):         ans.append(arr[i + 1][j - 1])     if isValidPos(i + 1, j, n, m):         ans.append(arr[i + 1][j])     if isValidPos(i + 1, j + 1, n, m):         ans.append(arr[i + 1][j + 1])      # Returning the list     return ans  arr = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] x, y = 1, 1 ans = getAdjacent(arr, x, y) print(" ".join(map(str, ans))) 
C#
using System; using System.Collections.Generic;  class GfG {      // Function to check whether     // position is valid or not     static int IsValidPos(int i, int j, int n, int m) {         if (i < 0 || j < 0 || i >= n || j >= m)             return 0;         return 1;     }      // Function that returns all adjacent elements     static List<int> GetAdjacent(int[,] arr, int i, int j) {          // Size of given 2d array         int n = arr.GetLength(0);         int m = arr.GetLength(1);          // Initialising a list where adjacent elements will be stored         List<int> ans = new List<int>();          // Checking for all the possible adjacent positions         if (IsValidPos(i - 1, j - 1, n, m) == 1)             ans.Add(arr[i - 1, j - 1]);         if (IsValidPos(i - 1, j, n, m) == 1)             ans.Add(arr[i - 1, j]);         if (IsValidPos(i - 1, j + 1, n, m) == 1)             ans.Add(arr[i - 1, j + 1]);         if (IsValidPos(i, j - 1, n, m) == 1)             ans.Add(arr[i, j - 1]);         if (IsValidPos(i, j + 1, n, m) == 1)             ans.Add(arr[i, j + 1]);         if (IsValidPos(i + 1, j - 1, n, m) == 1)             ans.Add(arr[i + 1, j - 1]);         if (IsValidPos(i + 1, j, n, m) == 1)             ans.Add(arr[i + 1, j]);         if (IsValidPos(i + 1, j + 1, n, m) == 1)             ans.Add(arr[i + 1, j + 1]);          // Returning the list         return ans;     }      public static void Main() {         int[,] arr = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} };         int x = 1, y = 1;         List<int> ans = GetAdjacent(arr, x, y);         Console.WriteLine(string.Join(" ", ans));     } } 
JavaScript
// Function to check whether // position is valid or not function isValidPos(i, j, n, m) {     if (i < 0 || j < 0 || i >= n || j >= m)         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 an array where adjacent elements will be stored     let ans = [];      // Checking for all the possible adjacent positions     if (isValidPos(i - 1, j - 1, n, m))         ans.push(arr[i - 1][j - 1]);     if (isValidPos(i - 1, j, n, m))         ans.push(arr[i - 1][j]);     if (isValidPos(i - 1, j + 1, n, m))         ans.push(arr[i - 1][j + 1]);     if (isValidPos(i, j - 1, n, m))         ans.push(arr[i][j - 1]);     if (isValidPos(i, j + 1, n, m))         ans.push(arr[i][j + 1]);     if (isValidPos(i + 1, j - 1, n, m))         ans.push(arr[i + 1][j - 1]);     if (isValidPos(i + 1, j, n, m))         ans.push(arr[i + 1][j]);     if (isValidPos(i + 1, j + 1, n, m))         ans.push(arr[i + 1][j + 1]);      // Returning the array     return ans; }  let arr = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]; let x = 1, y = 1; let ans = getAdjacent(arr, x, y); console.log(ans.join(" ")); 

Output
1 2 3 4 6 7 8 9 

Using For Loop - O(1) Time and O(1) Space

The idea is to define a directions array to store all eight directions, and run a loop to check all eight directions using single condition.

C++
#include <bits/stdc++.h> using namespace std;  // Function to check whether // position is valid or not int isValidPos(int i, int j, int n, int m) {     if (i < 0 || j < 0 || i >= n || j >= m)         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();      vector<int> ans;      // directions     vector<vector<int>> dirs = {         {-1, -1}, {-1, 0}, {-1, 1},         {0, -1}, {0, 1},         {1, -1}, {1, 0}, {1, 1}     };      for (auto dir : dirs) {         int x = i + dir[0];         int y = j + dir[1];         if (isValidPos(x, y, n, m))             ans.push_back(arr[x][y]);     }      return ans; }  int main() {     vector<vector<int>> arr =      {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};     int x = 1, y = 1;     vector<int> ans = getAdjacent(arr, x, y);     for (int i = 0; i < ans.size(); i++) {         cout << ans[i] << " ";     }     return 0; } 
Java
import java.util.*;  class GfG {      // Function to check whether     // position is valid or not     static int isValidPos(int i, int j, int n, int m) {         if (i < 0 || j < 0 || i >= n || j >= m)             return 0;         return 1;     }      // Function that returns all adjacent elements     static List<Integer> getAdjacent(int[][] arr, int i, int j) {          // Size of given 2d array         int n = arr.length;         int m = arr[0].length;          List<Integer> ans = new ArrayList<>();          // directions         int[][] dirs = {             {-1, -1}, {-1, 0}, {-1, 1},             {0, -1}, {0, 1},             {1, -1}, {1, 0}, {1, 1}         };          for (int[] dir : dirs) {             int x = i + dir[0];             int y = j + dir[1];             if (isValidPos(x, y, n, m) == 1)                 ans.add(arr[x][y]);         }          return ans;     }      public static void main(String[] args) {         int[][] arr = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};         int x = 1, y = 1;         List<Integer> ans = getAdjacent(arr, x, y);         for (int num : ans) {             System.out.print(num + " ");         }     } } 
Python
# Function to check whether # position is valid or not def isValidPos(i, j, n, m):     if i < 0 or j < 0 or i >= n or j >= m:         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])      ans = []      # directions     dirs = [         (-1, -1), (-1, 0), (-1, 1),         (0, -1), (0, 1),         (1, -1), (1, 0), (1, 1)     ]      for dx, dy in dirs:         x, y = i + dx, j + dy         if isValidPos(x, y, n, m):             ans.append(arr[x][y])      return ans  arr = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] x, y = 1, 1 ans = getAdjacent(arr, x, y) print(" ".join(map(str, ans))) 
C#
using System; using System.Collections.Generic;  class GfG {      // Function to check whether     // position is valid or not     static int IsValidPos(int i, int j, int n, int m) {         if (i < 0 || j < 0 || i >= n || j >= m)             return 0;         return 1;     }      // Function that returns all adjacent elements     static List<int> GetAdjacent(int[,] arr, int i, int j) {          // Size of given 2d array         int n = arr.GetLength(0);         int m = arr.GetLength(1);          List<int> ans = new List<int>();          // directions         int[,] dirs = {             {-1, -1}, {-1, 0}, {-1, 1},             {0, -1}, {0, 1},             {1, -1}, {1, 0}, {1, 1}         };          for (int k = 0; k < dirs.GetLength(0); k++) {             int x = i + dirs[k, 0];             int y = j + dirs[k, 1];             if (IsValidPos(x, y, n, m) == 1)                 ans.Add(arr[x, y]);         }          return ans;     }      public static void Main() {         int[,] arr = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} };         int x = 1, y = 1;         List<int> ans = GetAdjacent(arr, x, y);         Console.WriteLine(string.Join(" ", ans));     } } 
JavaScript
// Function to check whether // position is valid or not function isValidPos(i, j, n, m) {     if (i < 0 || j < 0 || i >= n || j >= m)         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;      let ans = [];      // directions     let dirs = [         [-1, -1], [-1, 0], [-1, 1],         [0, -1], [0, 1],         [1, -1], [1, 0], [1, 1]     ];      for (let dir of dirs) {         let x = i + dir[0];         let y = j + dir[1];         if (isValidPos(x, y, n, m))             ans.push(arr[x][y]);     }      return ans; }  let arr = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]; let x = 1, y = 1; let ans = getAdjacent(arr, x, y); console.log(ans.join(" ")); 

Output
1 2 3 4 6 7 8 9 

Next Article
XOR of major diagonal elements of a 3D Matrix
author
yashguptaaa333
Improve
Article Tags :
  • Matrix
  • DSA
  • Arrays
  • Interview-Questions
Practice Tags :
  • Arrays
  • Matrix

Similar Reads

  • Common elements in all rows of a given matrix
    Given an m x n matrix, find all common elements present in all rows in O(mn) time and one traversal of matrix. Example: Input:mat[4][5] = {{1, 2, 1, 4, 8}, {3, 7, 8, 5, 1}, {8, 7, 7, 3, 1}, {8, 1, 2, 7, 9}, };Output: 1 8 or 8 18 and 1 are present in all rows.A simple solution is to consider every el
    7 min read
  • Find the Peak Element in a 2D Array/Matrix
    Given a 2D Array/Matrix mat[][], the task is to find the Peak element. An element is a peak element if it is greater than or equal to its four neighbors, left, right, top and bottom. A peak element is not necessarily the overall maximal element. It only needs to be greater than existing adjacent Mor
    12 min read
  • Making all elements of matrix equal to a given element K
    Given a 2-d array arr[][], the task is to check whether it is possible to make all elements of the array to equal to a given number k if, in one operation, any element can be chosen and the surrounding diagonal elements can be made equal to it. Examples: Input: arr[][] = 1 8 3 1 2 2 4 1 9k = 2Output
    7 min read
  • Min, Max and Mean of Off-Diagonal Elements in a Matrix in R
    A matrix is a combination of elements stacked together in either row or column format. A table-like structure formed of similar data type elements is known as a matrix. A matrix has two diagonals, one of which is known as the main diagonal.  The main diagonal elements are characterized by the proper
    3 min read
  • XOR of major diagonal elements of a 3D Matrix
    Given a 3D matrix mat[][][] of dimensions N * N * N consisting of positive integers, the task is to calculate Bitwise XOR of all matrix elements present in the major diagonal. Examples: Input: arr[][][] = {{{1, 2}, {3, 4}}, {{5, 6}, {7, 8}}}Output: 12Explanation: The major diagonal elements are {1,
    9 min read
  • Program to find sum of elements in a given 2D array
    Given a 2D array of order M * N, the task is to find out the sum of elements of the matrix. Examples: Input: array[2][2] = {{1, 2}, {3, 4}};Output: 10 Input: array[4][4] = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}, {13, 14, 15, 16}};Output: 136 Approach: The sum of each element of the 2D array ca
    12 min read
  • Find maximum element of each row in a matrix
    Given a matrix mat[][], the task is to find the maximum element of each row. Examples: Input: mat[][] = [[1, 2, 3] [1, 4, 9] [76, 34, 21]]Output :3976Input: mat[][] = [[1, 2, 3, 21] [12, 1, 65, 9] [1, 56, 34, 2]]Output :216556 The idea is to run the loop for no_of_rows. Check each element inside the
    4 min read
  • Print Boundary Elements of a Matrix in JavaScript
    Matrixes are basic data structures that are frequently used to represent grids or tables of numbers. Gathering and showing the elements that are positioned along a matrix's edges is the process of printing the matrix's boundary elements. There are several approaches in JavaScript to print the bounda
    3 min read
  • Find the two repeating elements in a given array
    Given an array arr[] of N+2 elements. All elements of the array are in the range of 1 to N. And all elements occur once except two numbers which occur twice. Find the two repeating numbers. Examples: Input: arr = [4, 2, 4, 5, 2, 3, 1], N = 5Output: 4 2Explanation: The above array has n + 2 = 7 eleme
    15+ min read
  • Minimum element of each row and each column in a matrix
    Given a matrix, the task is to find the minimum element of each row and each column. Examples: Input: [1, 2, 3] [1, 4, 9] [76, 34, 21] Output: Minimum element of each row is {1, 1, 21} Minimum element of each column is {1, 2, 3} Input: [1, 2, 3, 21] [12, 1, 65, 9] [11, 56, 34, 2] Output: Minimum ele
    11 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences