2016-02-27 58 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(); 
    }