Hi. I have to write a program that solves the Knight's Tour in C++. The Knight's tour is where the Knight Chess piece has to move to every space on the chessboard only once. I am new to programming and I'm having trouble figuring out why my program has stopped after 20 moves. Also I am not sure how to keep all moves on the board itself. If there is anyone that could give me some idea on what is wrong it would be greatly appreciated.

#include <iostream>
using namespace std;

//global variables
const int columns = 8;
const int rows = 8; 

void displayBoard(int [][columns]);

int main()
{

	
	int horizontal [rows] = {2, 1, -1, -2, -2, -1, 1, 2};
	int vertical [columns] = {-1, -2, -2, -1, 1, 2, 2, 1};
	int count = 1;
	int currentRow =3;
	int currentColumn =4;
	int moveNumber= 1;
	int lastRow;
	int lastCol;
	int squaresLeft = 64;
	int gameBoard[rows][columns];


	for(int a= 0; a< rows; a++)
	{
		for (int b = 0; b< columns; b++)
		{
			gameBoard[a][b] = 0;
		}
	}
	
	displayBoard (gameBoard);
	cout<<endl;

	gameBoard[currentRow][currentColumn]= count;
	count++;

	while (squaresLeft)
	{
		if (count <=64)
		{
			lastRow = currentRow;
			lastCol = currentColumn;

			currentRow += vertical[moveNumber];
			currentColumn += horizontal[moveNumber];

			if ( gameBoard[currentRow][currentColumn] != 0)
			{	
				currentRow = lastRow;
				currentColumn = lastCol;
				moveNumber++;
			}
			else
			{	
				gameBoard[currentRow][currentColumn] = count;
				count++;
				moveNumber = 1;
			}
		}
		squaresLeft--;
	}
	displayBoard (gameBoard);




}

void displayBoard(int board[][columns])
{
	for (int i = 0; i < rows; i++)
	{
		for (int j = 0; j < columns; j++)
			cout << board[i][j]<<"  ";
			
		cout << endl;
	}

}

Recommended Answers

All 2 Replies

I'm having trouble figuring out why my program has stopped after 20 moves.

Looks like you decrement squaresLeft even when the square you test has already been used.

Also I am not sure how to keep all moves on the board itself.

Test. After adding vertical[] and horizontal[] to your location, test to see if it's on the board.

Thank you so much for your help. I figured it out. :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.