I’m in the process of trying to understand recursion better, so I decided to write a program to determine the shortest paths to all fields on an N * N game board, using recursion (I know BFS would be faster here, this is just for the sake of learning):
void visit(int x, int y, int moves)
{
if (x < 0 || x >= n || y < 0 || y >= n) {
return; // out of board
} else if (board[y][x] != -1) {
// already visited, check if path is shorter
if (moves < board[y][x]) board[y][x] = moves;
return;
} else {
// first time visiting
board[y][x] = moves;
visit(x + 1, y, moves + 1); // right
visit(x, y + 1, moves + 1); // down
visit(x, y - 1, moves + 1); // up
visit(x - 1, y, moves + 1); // left
}
}
# called with visit(0, 0, 0), so it should be able to start at any field
However, for a 3×3 board, it yields the following board:
0 1 2
1 2 3
6 5 4
The first two rows are right, however, the last row (except the last column in the last row) is wrong. It should be:
0 1 2
1 2 3
2 3 4
Here’s a 4×4 board:
0 1 2 3
1 2 3 4
12 9 6 5
13 8 7 6
Returning here is wrong. You’ve just lowered the score on this path—there are probably other paths in the area whose scores could be lowered:
Works as expected.