Backtracking: "Backtrack" To The Junction. at This Point in Time You Know That
Backtracking: "Backtrack" To The Junction. at This Point in Time You Know That
Junction
------------------------ portion A
|
|
|
portion B
Clearly, at a single junction you could have even more than two
choices. The backtracking strategy says to try each choice, one
after the other, if you ever get stuck, "backtrack" to the
junction and try the next choice. If you try all choices and
never found a way out, then there IS no solution to the maze.
Eight Queens Problem
In chess, queens can move all the way down any row, column
or diagonal (so long as no pieces are in the way).
Due to the first two restrictions, it's clear that each row and
column of the board will have exactly one queen.
int i;
if (location == SIZE) {
printSol(perm);
}
if (usedList[i].selected == 0) {
perm[location] = usedList[i].row;
usedList[i].selected = 1;
solveItRec(perm, location+1, usedList);
usedList[i].selected = 0;
}
}
}
}
Sudoku and Backtracking
1) Scan the board to look for an empty square that could take
on the fewest possible values based on the simple game
constraints.
2) If you find a square that can only be one possible value, fill it
in with that one value and continue the algorithm.
3) If no such square exists, place one of the possible numbers
for that square in the number and repeat the process.
4) If you ever get stuck, erase the last number placed and see if
there are other possible choices for that slot and try those next.
In dealing with a maze, to make sure you don't try too many
possibilities, one should mark which locations in the maze have
been visited already so that no location in the maze gets visited
twice. (If a place has already been visited, there is no point in
trying to reach the end of the maze from there again.