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 },
{ 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):