c++ - 使用递归的骑士巡回算法

标签 c++ algorithm knights-tour

我一直在编写代码来解决奈特的游览问题。我写了这段代码,现在有点困惑。我重新阅读并分析了几次,但未能找到导致问题的错误。我将不胜感激任何帮助。

#include <iostream>
const int N = 5; // size of table
int moves_table[2][8] = { { 1, 2, 2, 1, -1, -2, -1, -1 }, { -2, -1, 1, 2, -1, -2, -2, -1 } }; //my moves table that i use to increment or decrement my x and y cordinates
int THETABLE[N][N] = { 0 }; //all elements of table equal to zero
bool iknight_tour(int x, int y, int r); // this function will return true if Knight is able to be on every place on chessmate, without being twice at the same place, starting from TABLE[x][y]
bool if_move_correct(int x, int y); //checks if move can be done
int main()
{
    bool some_variable = iknight_tour(0, 0, 1); 
    for (int i = 0; i < N; i++)
    {
        for (int j = 0; j < N; j++)
        {
            std::cout << THETABLE[i][j] << "\t";
        }
        std::cout << std::endl;
    }
    std::cout << std::endl;
    std::cout << some_variable;
    std::cout << std::endl;

    return 0;
}
bool if_move_correct(int x, int y)
{
    if (x < N && x >= 0 && y < N && y >= 0 && THETABLE[x][y] == 0)
    {
        return true;
    }
    else
    {
        return false;
    }
}
bool iknight_tour(int x, int y, int r)
{
    THETABLE[x][y] = r;
    if (r == N*N)
    {
        return true;
    }
    else
    {
        for (int i = 0; i < 8; i++)
        {
            {
                if ((if_move_correct(x + moves_table[0][i], y + moves_table[1][i]))==true)
                {
                    if((iknight_tour(x + moves_table[0][i], y + moves_table[1][i], r + 1))==true)
                    {
                        return true;
                    }
                }   
            }
        }
        THETABLE[x][y] = 0;
    }   
    return false;
}

例如对于 i_kinghtour(0,0,1) 我得到:
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0

我应该得到:
1 20 17 12 3
16 11 2 7 18
21 24 19 4 13
10 15 6 23 8
25 22 9 14 5

最佳答案

这会移动表格:

int moves_table[2][8] = { { 1,  2,  2, 1, -1, -2, -1, -1 }, 
                          { -2, -1, 1, 2, -1, -2, -2, -1 } }; 

看起来很奇怪。 -1,-1 出现两次,-2,-2 出现。

也许它会更好地工作:

int moves_table[2][8] = { { 1,  2,  2, 1, -1, -2, -2, -1 }, 
                          { -2, -1, 1, 2, -2, -1,  1,  2 } }; 

关于c++ - 使用递归的骑士巡回算法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20181641/

相关文章:

c++ - 使用 QNetworkAccessManager 的插槽错误

c++ - 类方法的模板特化。 "Function template already defined"

c++ - 数组中第 k 个最大的元素

algorithm - Haskell:如果我尝试超过 55 步,Knight tour 永远不会结束?

c++ - Knight's Tour C++ 使用堆栈

lisp - 骑士之旅回溯 Lisp

c++ - 将回调传递给组件列表的包装器 c++

c++ - 我不明白我在取消分配内存时做错了什么

algorithm - 动态规划斐波那契算法

algorithm - 未排序数组中总和小于等于目标的最大元素数(未排序)