Quote:
Looking for assistance on recurssive knight's tour
Many errors in your code.
void moveKnight(int row, int col)
{
if (moveNum == 64)
{
print();
return;
}
if ((board[row - 2][col - 1] == 0) && checkBounds(row - 2, col - 1) == true)
{
board[row - 2][col - 1] = moveNum;
moveNum++;
totalMoves++;
(moveKnight(row - 2, col - 1));
}
Thus 64 is never written to a cell.
if ((board[row - 2][col - 1] == 0) && checkBounds(row - 2, col - 1) == true)
First you check if cell is available, and then you check if cell is within board.
You need to first check if within board, and then cell is available.
Here you are lucky, the mistake is not armful , but reading outside of board may lead to reading in a place you do not own and get a crash for this reason.
Then the worst is you recursion:
The problem is that you get out of recursion for 2 different reasons:
- First: the goal is reached and you want to got out of recursion without changing the board.
- Second: you reached a dead end and want to backtrack and
change your move.
Changing a move means cancel last move and try another.
So you have to free last cell and decrement moveNum.
I fear you need to rethink your code to cope with problems I described above.
Advice: instead of repeating same code 8 times for the 8 moves of the knight, it would be wise to use a table and loop on it instead.
Quote:
As you can see looking at various points, this fails to accomplish the goal. I've gone through my code several times now and I can't figure out what to do the fix this problem.
Make sure your code is doing what you expect, use the debugger
Your code do not behave the way you expect, or you don't understand why !
There is an almost universal solution: Run your code on debugger step by step, inspect variables.
The debugger is here to show you what your code is doing and your task is to compare with what it should do.
There is no magic in the debugger, it don't know what your code is supposed to do, it don't find bugs, it just help you to by showing you what is going on. When the code don't do what is expected, you are close to a bug.
To see what your code is doing: Just set a breakpoint and see your code performing, the debugger allow you to execute lines 1 by 1 and to inspect variables as it execute.
Debugger - Wikipedia, the free encyclopedia[
^]
Mastering Debugging in Visual Studio 2010 - A Beginner's Guide[
^]
Basic Debugging with Visual Studio 2010 - YouTube[
^]
1.11 — Debugging your program (stepping and breakpoints) | Learn C++[
^]
The debugger is here to only show you what your code is doing and your task is to compare with what it should do.