Question

I have been writing code to solve Knight's tour problem. I wrote this code and i am little confused now. I read and analyze it all over again,several times and was not able to find an error that causes the problem. I will appreciate any help.

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

For example for i_kinghtour(0,0,1) i got :
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

And i should get:
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

Was it helpful?

Solution

This moves table:

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

looks very odd. You have -1,-1 appearing twice, and -2,-2.

Perhaps it would work better with:

int moves_table[2][8] = { { 1,  2,  2, 1, -1, -2, -2, -1 }, 
                          { -2, -1, 1, 2, -2, -1,  1,  2 } }; 
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top