需要工作的C#代码在二维数组中查找元素的邻居

问题描述

| 说12行10列的数组
int[,] array = new int[12,10];
并且我选择0,0它必须返回0,0的所有邻居 这将是
0,1
1,0
说我要2,3的邻居,它必须返回邻居数组
1,2
1,3
1,4
2,2
2,4
3,1
3,2
3,3
    

解决方法

死脑筋且表现欠佳,但说明性且快速:
        int[,] array = new int[12,10];

        int refx=0,refy=10;

        var neighbours = from x in Enumerable.Range(0,array.GetLength(0)).Where(x => Math.Abs(x - refx)<=1)
                         from y in Enumerable.Range(0,array.GetLength(1)).Where(y => Math.Abs(y - refy)<=1)
                         select new {x,y};

        neighbours.ToList().ForEach(Console.WriteLine);
或者
        neighbours = from x in Enumerable.Range(refx-1,3)
                     from y in Enumerable.Range(refy-1,3)
                     where x>=0 && y>=0 && x<array.GetLength(0) && y<array.GetLength(1)
                     select new {x,y};

        neighbours.ToList().ForEach(Console.WriteLine);
    ,
element [x,y]

neighbor1 = x + 1,y;
neighbor2 = x - 1,y;
neighbor3 = x,y + 1;
neighbor4 = x,y - 1;
neighbor5 = x + 1,y + 1;
neighbor6 = x + 1,y - 1;
neighbor7 = x - 1,y + 1;
neighbor8 = x - 1,y - 1;
显然,您需要检查那些元素坐标是否存在,以防万一该元素位于矩阵的“ border”中。硬?我拒绝。