2016-02-27 57 views
1

(我可以用一个铁血或多维数组我只是指一个铁血此问题)在阵列查找附近的值

我有一个交错数组[] []具有这样的

1 3 1 1 1 
1 3 3 3 1 
1 1 2 1 1 
1 3 1 3 1 
1 1 1 1 1 

现在我想要找到紧接着2个5个3和3个1的值旁边的值我从哪里开始,对于我的生活我甚至不知道从哪里开始。

+1

查找'我,价值j'指数需要。并访问像这样的'arr [i-1] [j],arr [i + 1] [j]'等附近的值。当然,您需要通过检查计算的索引是否在数组边界来处理边界情况。 –

+1

[需要工作的C#代码来查找二维数组中的元素的邻居](http://stackoverflow.com/questions/5640538/need-working-c-sharp-code-to-find-neighbors一个二维的ARR) –

回答

1

如果2是AR [i] [j],那么你就可以搜索与2相邻位置的周期是这样的:

for (int x = i - 1; x <= i + 1; x++) {  
    for (int y = j - 1; y <= j + 1; y++) { 
     if (x == i && y == j) 
      continue; // skip the position where your 2 is 
     // do your logic here - count the value at ar[x][y] 
    } 
} 

而且要小心处理您的数组的边界(唐试图访问数组之外​​的元素)。

我希望这会指出你在正确的方向。

0
for (int x = i - 1; x <= i + 1; x++) 
{ 

    for (int y = j - 1; y <= j + 1; y++) 
    { 

     if (x == i && y == j) 
     // do something here 
    } 
} 

,或者你可以使用2 while循环就会使同样的效果

+0

我不认为这真的回答了这个问题。我和j是什么? –

+0

他需要的价值指数。 –

1

事情是这样的,如果使用LINQ:

static void Main(string[] args) 
    { 
     int[,] array2D = new int[,]{ 
     { 1, 3, 1, 1, 1 }, 
     { 1, 3, 3, 3, 1 }, 
     { 1, 1, 2, 1, 1 }, 
     { 1, 3, 1, 3, 1 }, 
     { 1, 1, 1, 1, 1 }}; 
     var resultList = GetNearbyValues(array2D, 2, 2); 
    } 

    private static List<int> GetNearbyValues(int[,] array2D, int i, int j) 
    { 
     var values = from x in Enumerable.Range(i - 1, i + 1) 
        from y in Enumerable.Range(j - 1, j + 1) 
        // make sure x and y are all positive 
        where x >= 0 && y >= 0 && (x != i | y != j) 
        select array2D[x, y]; 
     return values.Cast<int>().ToList(); 
    }