As part of some procedural generation code, I have a function that checks if a cell in a grid has any neighbouring cells.
The grid is a 2D array, if it was printed it would look like this (# = cell and . = empty and the # around the edge is a border):
0123456789
0##########
1#........#
2#........#
3#........#
4#........#
5#....##..#
6#........#
7#........#
8#........#
9##########
So, for example, my code returns true if it checks cell 5,5.
The code I have written for checking for neighbouring cells works, but does not take into account if the cell it is checking is at the "edge" (eg. 0,0 or 0,1 or 10,10) and will create out of bound errors if it does check cells at the edge. I'm unsure of how to go about writing code that does take this into account, any advice would be appreciated.
This is my code so far:
public static bool HasNeighbour(int[,] array, int CellX, int CellY)
{
if (array[CellX + 1, CellY] == 1)
{
return true;
}
if (array[CellX - 1, CellY] == 1)
{
return true;
}
if (array[CellX, CellY + 1] == 1)
{
return true;
}
if (array[CellX, CellY - 1] == 1)
{
return true;
}
if (array[CellX + 1, CellY + 1] == 1)
{
return true;
}
if (array[CellX + 1, CellY - 1] == 1)
{
return true;
}
if (array[CellX - 1, CellY + 1] == 1)
{
return true;
}
if (array[CellX - 1, CellY - 1] == 1)
{
return true;
}
return false;
}
Also, is there a more efficient version of my code?
Thanks