Investigate the 8 fields arround every field in two dimensional array?

How to check the 8 neighbours of the field? I mean some fields have just 3 neighbours, because they are on the border of the array. thanks for help

Jon Skeet
people
quotationmark

Yes, so you need to take account of that by checking for the row and column values being 0 or the height/width. If you're just adding up values, you may find it easiest to have a method which just returns the value in the array, or 0 if you're asking for a value out of range:

int GetValue(int[,] array, int x, int y)
{
    if (x < 0 || y < 0 ||
        x >= array.GetLength(0) || y >= array.GetLength(1))
    {
        return 0;
    }
    return array[x, y];
}

Then you can just use:

for (int x = 0; x < array.GetLength(0); x++)
{
    for (int y = 0; y < array.GetLength(0); y++)
    {
        int total = GetValue(array, x - 1, y - 1)
                  + GetValue(array, x, y - 1)
                  + GetValue(array, x + 1, y - 1)
                  + GetValue(array, x - 1, y)
                  + GetValue(array, x + 1, y)
                  + GetValue(array, x - 1, y + 1)
                  + GetValue(array, x, y + 1)
                  + GetValue(array, x + 1, y + 1);
        // Do something with the total
    }
}

Note that all the calls to GetLength are pretty inefficient here. There are alternatives which would be more efficient, but a bit more complicated.

people

See more on this question at Stackoverflow