For a project I have procedurally generated a series of 'tiles' with coordinates from (0,0) --> (x, y) where (x,y) is the maximum width and height of the tile array. This tile array is then populated randomly with squares and is given an entrance and multiple exit points. I am trying to create an algorithm which, given a starting point, checks whether all the exit points can be reached. To do this, each tile contains data regarding their N-E-S-W adjacent tiles, and a recursive function is called which checks the current tile for an exit, then moves to the North tile, then does the same for East, West, then South.
Here is a (pseudo) example of the code except instead of checking for exits it visits all available tiles and counts them (or it's meant to):
public class Algo
{
public int Count(Tile tile)
{
tile.Visited = true;
foreach (direction in NESW)
{
if(!tile.direction.IsPopulated & !tile.direction.Visited)
{
return Count(tile.direction) + 1;
}
}
return 0;
}
}
IsPopulated
is a boolean which returns true if a tile is populated with a square, Visited is boolean which returns true if the tile has been visited. There is a perimeter of squares around the tile space which ensures the algorithm stays within the bounds of the tile space
For a tile layout like this:
The algorithm returns 17 instead of the expected 21.
It seems as though, when the algorithm reaches a tile which cannot move in any direction, the function returns the count, instead of returning to the call stack and trying again.
Another version I have tried works as expected, however, it is not fruitful and mutates a member variable of the class outside of the method.
public class Algo2
{
count = 0;
public void Count(Tile tile)
{
tile.Visited = true;
count += 1;
foreach (direction in NESW)
{
if(!tile.direction.IsPopulated & !tile.direction.Visited)
{
return Count(tile.direction);
}
}
}
}
This returns a value of 21 and works as expected.
Why does the non-fruitful recursive function with side-effects work, while the fruitful function with no side-effects does not?