Coding Find the average of neighbours in the 2-D matrix Given the matrix, output the average array matrix where each element represents the average of surrounding neighbors. Varun Chopra Read more posts by this author. Varun Chopra 15 Nov 2020 • 1 min read IntroductionGiven the matrix, output the average array matrix where each element represents the average of surrounding neighbors.Input: {1, 2, 3, 4}, {6, 7, 8, 9}, {2, 3, 4, 5} Output: 5 5 6 8 4 4 5 6 6 6 7 8 Explanation For the entry 7 located at (1, 1) 1 2 3 6 7 8 2 3 4 Sum = 36 and Count = 9 Average = 4Example CaseApproachThe approach is to create a sum array and fill it by calculating sum and count from the neighbors.Codeusing System; using System.Collections.Generic; using System.Text; namespace ConsoleApp1 { class CorruptImage { public static void Run() { var image = new[,] { {1, 2, 3, 4}, {6, 7, 8, 9}, {2, 3, 4, 5} }; var res = PerformCorruptImage(image); for (int i = 0; i < res.GetLength(0); i++) { for (int j = 0; j < res.GetLength(1); j++) { Console.Write(res[i, j] + " "); } Console.WriteLine(); } } private static readonly int[][] PossibleMoves = { new []{-1, 0}, new []{-1, -1}, new []{0, -1}, new []{1, -1}, new []{1, 0}, new []{1, 1}, new []{0, 1}, new []{-1, 1}, }; private const int X = 0; private const int Y = 1; private static int[,] PerformCorruptImage(int[,] image) { var m = image.GetLength(0); var n = image.GetLength(1); var corruptImage = new int[m, n]; for (var i = 0; i < m; i++) { for (var j = 0; j < n; j++) { var sum = image[i, j]; var count = 0; foreach (var move in PossibleMoves) { var pointX = move[X] + i; var pointY = move[Y] + j; if (pointX < 0 || pointY < 0 || pointX >= m || pointY >= n) { continue; } sum += image[pointX, pointY]; count++; } corruptImage[i, j] = sum / count; } } return corruptImage; } } } C# Program to print average of the matrix