Visit neighbor of a position in a 2d-array
I have the following two dimensional array:
static int[,] arr = new int[5, 5]
{
{ 00, 00, 00, 01, 00 },
{ 00, 00, 01, 01, 00 },
{ 00, 00, 01, 01, 00 },
{ 00, 00, 01, 01, 00 },
{ 00, 00, 00, 01, 00 },
};
I have to a implement a method called Hit(int x, int y). When we hit a 0 in the array (i.e. Hit(0, 0), Hit(1, 1), but not Hit(3, 0)) I would like all the adjacent zeros to the zero we hit to be incremented by 10. So if I call Hit(1, 1), the array should become the following.
static int[,] arr = new int[5, 5]
{
{ 10, 10, 10, 01, 00 },
{ 10, 10, 01, 01, 00 },
{ 10, 10, 01, 01, 00 },
{开发者_如何学C 10, 10, 01, 01, 00 },
{ 10, 10, 10, 01, 00 },
};
Any idea how I could implement that? It sounds to me like a Depth First Search/Recursive sort-of algorithm should do the job, but I haven't been able to implement it for an 2d array.
Thanks for the help!
What you are looking for is a Flood fill algorithm, which you can implement in various ways, from DFS (watch the stack) to BFS.
You can also tighten the code a little bit, but here's a rough sketch of what I would do (with DFS):
int[] dx = { 1, 1, 1, 0, 0, -1, -1, -1 };
int[] dy = { 1, 0, -1, 1, -1, 1, -1, 0 };
void Hit( int x, int y ) {
if ( board[x,y] == 0 ) {
board[x,y] = 10;
for ( int i = 0; i < 8; i++ ) {
nx = x + dx[i];
ny = y + dy[i];
// if nx, ny is in bound
if ( nx >= 0 && nx < height && ny >= 0 && ny < height )
Hit( nx, ny );
}
}
}
I would say that you should be able to so this with a recursive method.
Something like
private void Hit(int[,] arr, int x, int y)
{
if (
x < 0 ||
x + 1 > arr.GetLongLength(0)||
y < 0 ||
y + 1 > arr.GetLongLength(1)
)
return;
if (arr[x, y] == 0)
{
arr[x, y] += 10;
Hit(arr, x, y + 1);
Hit(arr, x + 1, y + 1);
Hit(arr, x + 1, y);
Hit(arr, x + 1, y - 1);
Hit(arr, x, y - 1);
Hit(arr, x - 1, y - 1);
Hit(arr, x - 1, y);
}
}
Personally I think it's odd to do this with a recursive method. I'd just treat it as an image processing task and run a filter across the array.
精彩评论