0

I am trying to solve Knight Tour Problem using recursive Backtracking. Can someone help me optimize my code. My code works till 6X6 board. . After N=7 it takes almost infinite time to solve . Here is my code :

#include <iostream>
#include "genlib.h"
#include "grid.h"
#include "vector.h"
#include <iomanip>

const int NOT_VISITED = -1;
//Size of the board
const int N = 6;
const int N2 = N*N;

typedef Grid<int> chess;

struct position{
    int row;
    int col;
};

//Initializes the board and makes each and every
//square value as NOT_VISITED
void initializeBoard(chess &board)
{
    for(int i=0;i<board.numRows();i++)
        for(int j=0;j<board.numCols();j++)
            board[i][j] = NOT_VISITED;
}

//Returns true if the square is visited;
bool visited(chess &board,position square)
{
    return board[square.row][square.col ] != NOT_VISITED;
}

//Returns true if the givien position variable is outside the chess board
bool outsideChess(chess &board, position square)
{
    if(square.row <board.numRows() && square.col <board.numCols() && square.row >=0 && square.col >=0)
        return false;
    return true;
}

void visitSquare(chess &board,position square,int count)
{
    board[square.row] [square.col] = count;
}

void unVisitSquare(chess &board,position square)
{
    board[square.row] [square.col] = NOT_VISITED;
}

position next(position square,int irow, int icol)
{
    square.row += irow;
    square.col += icol;
    return square;
}
Vector<position> calulateNextSquare(chess board,position square)
{
    Vector<position> list;
    for(int i=-2;i<3;i=i+4)
    {
        for(int j=-1;j<2;j=j+2)
        {
            list.add(next(square,i,j));
            list.add(next(square,j,i));
        }
    }
    return list;

}

bool knightTour(chess &board,position square, int count)
{
    //cout<<count<<endl;
    //Base Case if the problem is solved;
    if(count>N2)
        return true;
    if(outsideChess(board,square))
        return false;
    //return false if the square is already visited
    if(visited(board,square))
        return false;
    visitSquare(board,square,count);
    Vector<position> nextSquareList = calulateNextSquare(board,square); 
    for(int i=0;i<nextSquareList.size();i++)
        if(knightTour(board, nextSquareList[i], count+1))
            return true;
    unVisitSquare(board,square);
    return false;
}


void printChess(chess &board)
{
    for(int i=0;i<board.numRows();i++)
    {
        for(int j=0;j<board.numCols();j++)
            cout<<setw(4)<<board[i][j];
        cout<<endl;
    }
}


int main()
{
    chess board(N,N);
    initializeBoard(board);
    position start;
    start.row = 0; start.col = 0;
    if(knightTour(board,start,1))
        printChess(board);
    else
        cout<<"Not Possible";
    return 0;
}

i am using Stanford 106B Libraries( grid is a 2 dimensional vector ) Visual studio 2008 Blank project with required library files https://docs.google.com/viewer?a=v&pid=explorer&chrome=true&srcid=0BwLe9NJT8IreNWU0N2M5MGUtY2UxZC00ZTY2LWE1YjQtMjgxYzAxMWE3OWU2&hl=en

false
  • 10,264
  • 13
  • 101
  • 209
Ganesh
  • 57
  • 8
  • Ran for half an hour still couldn't get output for 8X8..Even though its not infinity but still its lot of time for such a problem ... – Ganesh Oct 06 '11 at 16:05

3 Answers3

1

I'd say, for a start, get rid of this:

Vector<position> nextSquareList = calulateNextSquare(board,square);

creating a Vector on each step will take a lot of time. You could either use an array (fixed sized, since you know there are 8 possible moves), or unroll the loop entirely. Compare with this version, similar to yours.

jpalecek
  • 47,058
  • 7
  • 102
  • 144
0

Some modifications I would like to suggest:

#include <iostream>
#include "genlib.h"
#include "grid.h"
#include "vector.h"
#include <iomanip>

const int NOT_VISITED = -1;
//Size of the board
const int N = 6;
const int N2 = N*N;

typedef int chess[N][N]; // <------------- HERE

struct position{
    int row;
    int col;
};

//Initializes the board and makes each and every
//square value as NOT_VISITED
void initializeBoard(chess &board)
{
    for(int i=0;i<board.numRows();i++)
        for(int j=0;j<board.numCols();j++)
            board[i][j] = NOT_VISITED;
}

//Returns true if the square is visited;
bool visited(chess &board,position square)
{
    return board[square.row][square.col ] != NOT_VISITED;
}

//Returns true if the givien position variable is outside the chess board
bool outsideChess(chess &board, position square)
{
    if(square.row <board.numRows() && square.col <board.numCols() && square.row >=0 && square.col >=0)
        return false;
    return true;
}

void visitSquare(chess &board,position square,int count)
{
    board[square.row] [square.col] = count;
}

void unVisitSquare(chess &board,position square)
{
    board[square.row] [square.col] = NOT_VISITED;
}

position next(position square,int irow, int icol)
{
    square.row += irow;
    square.col += icol;
    return square;
}
void calulateNextSquare(chess board,position square, Vector<position>& list)  // <------------- HERE
{
    // ------------- HERE
    //Also, change this part to add only unvisited and not out-of-board positions.
    for(int i=-2;i<3;i=i+4)
    {
        for(int j=-1;j<2;j=j+2)
        {
            list.add(next(square,i,j));
            list.add(next(square,j,i));
        }
    }
}

bool knightTour(chess &board,position square, int count)
{
    //cout<<count<<endl;
    //Base Case if the problem is solved;
    if(count>N2)
        return true;
    if(outsideChess(board,square))
        return false;
    //return false if the square is already visited
    if(visited(board,square))
        return false;
    visitSquare(board,square,count);
    Vector<position> nextSquareList;  // <------------- HERE
    calulateNextSquare(board,square,nextSquareList); 
    for(int i=0;i<nextSquareList.size();i++)
        if(knightTour(board, nextSquareList[i], count+1))
            return true;
    unVisitSquare(board,square);
    return false;
}


void printChess(chess &board)
{
    for(int i=0;i<board.numRows();i++)
    {
        for(int j=0;j<board.numCols();j++)
            cout<<setw(4)<<board[i][j];
        cout<<endl;
    }
}


int main()
{
    chess board(N,N);
    initializeBoard(board);
    position start;
    start.row = 0; start.col = 0;
    if(knightTour(board,start,1))
        printChess(board);
    else
        cout<<"Not Possible";
    return 0;
}

But please note that you still have a exponential complexity, and optimizing your code wont change it.

André Puel
  • 8,741
  • 9
  • 52
  • 83
  • This wouldn't help on any decent compiler with NRVO. – jpalecek Oct 06 '11 at 15:54
  • @jpalecek Sure, the main optimization I suggest was inside calculateNextSquare... To dont add what is invalid. – André Puel Oct 06 '11 at 17:07
  • you mainly changed the signature of calculateNextSquare, that wouldn't help. The changes inside claculateNextSquare (suggested by comment) robably wouldn't help much, either. – jpalecek Oct 06 '11 at 17:18
0

You are passing a copy of the board to calculateNextSquare but it seems you don't need it in this method.

Also, you return a vector in this method but you should pass it by reference.

Andrés Senac
  • 841
  • 6
  • 14
  • @Ganesh recursive backtracking is not the best way to resolve this problem. it spends a lot of time without using some heristics – Andrés Senac Oct 06 '11 at 19:59