Lately I've been stuck on an algorithm for "exploring a grid". I want to paint all moves that are valid within a certain part of a grid based on a starting square that could be anywhere on the grid. My original plan was to use recursive split off in 4 directions marking grids until it either reached a boundary or the move limit. An exploring "branch" cannot move diagonally:
*note: arrows do not represent occurrence in stack, they are there for visualizing the concept of the algorithm
private void Explore(byte moves, byte row, char col) {
if (row >= Grid[0].Count || col >= Grid.Count || row + col + 2 > moves) {//var < 0 handled b/c byte b = 0; (byte)(b-1) == 255
return;
}
Grid[row][col].color = ...;//mark it
if (Grid[row + 1][col + 1] == notVisited) Explore((byte) (moves - 1), (byte)(row + 1), (char) (col + 1));
if (Grid[row - 1][col + 1]== notVisited) Explore((byte)(moves - 1), (byte)(row - 1), (char) (col + 1));
if (Grid[row - 1][col - 1] == notVisited) Explore((byte)(moves - 1), (byte)(row - 1), (char) (col - 1));
if (Grid[row + 1][col - 1] == notVisited) Explore((byte)(moves - 1), (byte)(row + 1), (char) (col - 1));
}
I know this algorithm doesn't work b/c I did a quick runnable sample here where the algorithm gets stuck between values until it triggers a Runtime error.
So at this point:
Is recursion still a possibility (switch to iterative)?
Is there a better alternative algorithm to this problem?
Is my algorithm close, but needs a few tweaks?