c++ - 递归确定游戏板上所有字段的最小移动次数

标签 c++ c algorithm recursion

我正在尝试更好地理解递归,所以我决定编写一个程序来使用递归确定 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

前两行是正确的,但最后一行(最后一行的最后一列除外)是错误的。应该是:

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

最佳答案

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

返回这里是错误的。您刚刚降低了该路径上的分数 - 该区域中可能还有其他路径的分数可以降低:

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;
  }
}

按预期工作。

关于c++ - 递归确定游戏板上所有字段的最小移动次数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10336550/

相关文章:

algorithm - 按词典顺序生成排列与排序?

c++ - 如何在屏幕抓取中捕获鼠标光标?

c++ - 结构和数组的初始值设定项太多

c - 通过串联将位(字节)存储在 long long 中

python - 在 Python 中创建四个列表的所有可能组合的最有效方法?

algorithm - 检查一个矩形是否平分另一个矩形

c++ - 一劳永逸地理解 C 和 C++ 中 f() 和 f(void) 之间的区别

c++ - 类的私有(private) Load() 方法,它们是如何工作的

c - 使用memcpy时重叠的含义

没有反向引用的 C POSIX ERE