Question: 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 3x3 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 4x4 board:

```
0 1 2 3
1 2 3 4
12 9 6 5
13 8 7 6

```

Answer: 
```
else if (board[y][x] != -1) {
    // already visited, check if path is shorter
    if (moves &lt; board[y][x]) board[y][x] = moves;
    return;
}

```

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:

```
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 || moves < board[y][x]) {
    // first time visiting
    board[y][x] = moves;

    visit(x + 1, y, moves + 1);
    visit(x, y + 1, moves + 1);
    visit(x, y - 1, moves + 1);
    visit(x - 1, y, moves + 1);
  } else {
    return;
  }
}

```

Works as expected.
You are doing a depth first search which may find sub-optimal paths to some squares.

To get optimal paths, if your path is shorter you should still visit from it, even if it is already visited.