0

我一直在编写代码来解决骑士的旅行问题。我写了这段代码,现在我有点困惑。我重新阅读并分析了好几次,但无法找到导致问题的错误。我将不胜感激。

#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

4

1 回答 1

4

这移动表:

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 } }; 
于 2013-11-24T22:31:12.487 回答