Need working C# code to find neighbors of an element in a 2-dimentional array
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
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;
Obviously you need to check if those elements coordinates exists just in case the element is in a "border" of the matrix. Hard? I say no.
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);
精彩评论