I'm stuck at my first more complex coding task in C: developing a program that solves the knight's tour (chess, knight has to visit every field on the board only once) and it also should have a live display, showing which move the program is taking in real time.
The solution I came up with doesn't support live display though, as it is iterating through a for loop until the maximum number of moves has been reached, then prints the moves. How could I change this code to create real time output?
The displayBoard function is only printing a chessboard in the console output, with the current position of the knight as well as the field's name (e.g. A-1). Plan is to change this to a stream output for console, after my initial problem is solved.
(In conjunction to this question: how exactly does the function calling as if condition work? I stumbled upon this in the webs but sadly there was no explanation to it.)
int knight(int line, int row, int moveNumber)
{
int newLine, newRow, i;
//char cells[]={'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H'};
//mark visited cell
board[line][row] = moveNumber;
//for-loop for every possible move
for(i = 0; i < 8; i++)
{
//new position
newLine = line + moves[i][0];
newRow = row + moves[i][1];
//is the move on the board?
if(newLine >= 1 && newLine <= N && newRow >= 1 && newRow <= N)
{
//has the cell been visited yet?
if(!board[newLine][newRow])
{
//recursion until 63th move
if(moveNumber == max_moves || knight(newLine, newRow, moveNumber+1))
{
printf("Move %d: from %c-%d to %c-%d ", moveNumber, cells[row-1], line, cells[newRow-1], newLine);
boardDisplay(newLine, newRow);
return 1;
}
}
}
}
// free last visited cell, if there's no move possible anymore
board[line][row] = 0;
return 0;
}