Monday, 6 October 2014

Knight Tour Problem - BackTracking

The knight is placed on the first block of an empty board and,
moving according to the rules of chess, must visit each square exactly once




#include<stdlib.h>
#include<iostream>
#define N 8

int solveKnightTourUtil(int x, int y, int movei, int sol[N][N], int xMove[N], int yMove[N]);

int solveKTUtil(int x, int y, int movei, int sol[N][N], int xMove[],
    int yMove[]);

//check if i,j are valid indexes on N*N chess board
int isSafe(int x, int y, int sol[N][N])
{
    if (x >= 0 && x < N && y >= 0 && y < N && sol[x][y] == -1)
    {
        return 1;
    }
    return 0;
}

void printSolution(int sol[N][N])
{
    for (int x = 0; x < N; x++)
    {
        for (int y = 0; y < N; y++)
            printf(" %2d ", sol[x][y]);
        printf("\n");
    }
}

bool solveKnightTour(){
    int sol[N][N];

    //initialise solution matrix
    for (int x = 0; x < N; x++)
    for (int y = 0; y < N; y++)
        sol[x][y] = -1;

    // define next move of knight as xMove[] and yMove[]
   
    int xMove[8] = { 2, 1, -1, -2, -2, -1, 1, 2 };
    int yMove[8] = { 1, 2, 2, 1, -1, -2, -2, -1 };

    //knight is at first block
    sol[0][0] = 0;


    // xplore all tours using solveKnightTourUtil() starting from 0,0
    if (solveKnightTourUtil(0, 0, 1, sol, xMove, yMove) == false)
    {
        printf("Solution does not exist");
        return false;
    }
    else
        printSolution(sol);

    return true;
}


// recursive function to solve knight tour problem
int solveKnightTourUtil(int x, int y, int movei, int sol[N][N], int xMove[N], int yMove[N])
{
    int k, next_x, next_y;
    //solution vector completes
    if (movei == N*N)
        return true;

    //try all moves from cuurent position x, y
    for (k = 0; k < 8; ++k)
    {
        next_x = x + xMove[k];
        next_y = y + yMove[k];

        if (isSafe(next_x, next_y, sol))
        {
            sol[next_x][next_y] = movei;
            if (solveKnightTourUtil(next_x, next_y, movei + 1,sol, xMove, yMove))
                return true;

            else
                sol[next_x][next_y] = -1; //backtrack
        }
    }

    return false;
}



int main()
{
    solveKnightTour();
    getchar();
    return 0;
}

No comments:

Post a Comment