在数组中查找附近的值

Find nearby values in Array

(我可以使用 Jagged 或 Multidimensional Array 对于这个问题我将只引用 Jagged 数组)

我有一个 Jagged Array[][],它的值大约是这样的

 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 我该从哪里开始呢我什至不知道从哪里开始。

如果 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]
    }
}

还要小心处理数组的边界(不要尝试访问数组外的元素)。

我希望这会为您指明正确的方向。

如果使用 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();
    }