私は再帰をよりよく理解しようとしている最中なので、再帰を使用して、N * Nゲームボード上のすべてのフィールドへの最短経路を決定するプログラムを作成することにしました(ここではBFSの方が速いと思いますが、これは学習のために):
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
ただし、3x3ボードの場合、次のボードが生成されます。
0 1 2
1 2 3
6 5 4
最初の2行は正しいですが、最後の行(最後の行の最後の列を除く)は間違っています。そのはず:
0 1 2
1 2 3
2 3 4
これが4x4ボードです:
0 1 2 3
1 2 3 4
12 9 6 5
13 8 7 6