需要工作的C#code找到一个元素的邻居2维数组 [英] Need working C# code to find neighbors of an element in a 2-dimentional array

查看:183
本文介绍了需要工作的C#code找到一个元素的邻居2维数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说阵列12行和10列

  INT [,]数组=新INT [12,10]。

和我选择0,0它必须返回0,0所有邻居
这将是

  0,1
1,1
1,0

说我想要的2,3邻居它必须返回邻居的数组

  1,2
1,3
1,4
2,2
2,4
3,1
3,2
3,3


解决方案

新空房禁地和不良而是说明性的,快速的:

  INT [,]数组=新INT [12,10]。        INT REFX = 0,REFY = 10;        变种邻居从Enumerable.Range X =(0,array.GetLength(0))其中(x => Math.Abs​​(X  -  REFX)所述; = 1)。
                         从在Enumerable.Range Y(0,array.GetLength(1))其中(Y => Math.Abs​​(γ - REFY)所述; = 1)。
                         选择新的{X,Y};        。neighbours.ToList()的ForEach(Console.WriteLine);

或者

 从邻居中x = Enumerable.Range(REFX-1,3)
                     从在Enumerable.Rangeγ(REFY-1,3)
                     其中x> = 0&放大器;&放大器; Ÿ> = 0&放大器;&安培; X - 所述; array.GetLength(0)及&放大器; Y'LT; array.GetLength(1)
                     选择新的{X,Y};        。neighbours.ToList()的ForEach(Console.WriteLine);

say array with 12 rows and 10 columns

int[,] array = new int[12,10];

and I select 0,0 it must return all neighbors of 0,0 which will be

0,1
1,1
1,0

say I want neighbors of 2,3 it must return an array of neighbors

1,2
1,3
1,4
2,2
2,4
3,1
3,2
3,3

解决方案

Braindead and non-performing but illustrative and quick:

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

alternatively

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

这篇关于需要工作的C#code找到一个元素的邻居2维数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆