1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60
 
  | 
class knightTour
{
public:
    knightTour(int = 0);
    bool canPlaceKnight(int&, int&, int);     //function to determine if knight can be placed in a particular cell on chess board 
    bool moveWithinBounds(int, int, int);     //function to determine if knight move is within the bounds of the chess board
    bool traceKnightTour(int, int);           //function to trace the path of the knight; all cells must be visited, each at most once
    void printKnightTour();
    pair <int, int> indexToKnightMoveConverter(int);
 
private:
    int noOfCellsFilled;
    int boardSize;
    int** chessBoard;
};
bool knightTour::traceKnightTour(int row, int col)
{ 
    if (noOfCellsFilled < boardSize*boardSize)       
    {
        if (noOfCellsFilled == 0)
	{
	    chessBoard[row][col] = 1;
	    ++noOfCellsFilled;
	}
	for (int i = 0; i < 8; i++)
	{    
	    if (canPlaceKnight(row, col, i))       //determines the row-column coordinates of knight's cell    
	    {  
	        static queue<pair<int,int> > q;    //queue to hold row-column coordinates of the current and last cell entries      
		q.push(make_pair(row, col));        
		if (q.size() > 2)		//ensuring the queue size is 2
	            q.pop();			
                showQueueContents(q);      //function to display the contents of the queue 
                
                chessBoard[row][col] = ++noOfCellsFilled;    //fill cell with corresponding number
                if (traceKnightTour(row, col))      //recursive call
	            return true;
                
	        chessBoard[row][col] = 0;     //backtracking
	            
                showQueueContents(q);      //displaying queue contents after recursive call     
	            pair<int, int> temp;         
                if (!q.empty())     
	            temp = q.front();      //since we are backtracking, retrieve row-column pair of last cell filled from the queue
                
                row = temp.first;         //grab the row-column coordinates of the last cell filled
                col = temp.second;	
                cout<<"noOfCellsFilled = "<<noOfCellsFilled<<endl;    
                --noOfCellsFilled;
	    }	         
	}
	return false;	    
    }
    else     //all the cells of the chess board are filled
        return true;   
}
  |  |