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)); } }