The basic method of backtracking is to search, or a well-organized search method that can avoid unnecessary search. This method is suitable for solving problems with a large number of combinations.
In the solution space tree of a problem, the Backtracking Method searches for the solution space tree from the root node based on the depth priority policy. When the algorithm searches for any point in the solution space tree, it first determines whether the node contains the solution of the problem. If it is not included, search for the subtree with the root node is skipped and trace back to its ancestor node layer by layer. Otherwise, search for the subtree Based on the deep priority policy.
The guiding ideology of the Backtracking Method-if you cannot get through, you will turn around. Design Process: Determine the problem solution space, determine the node extension rules, and search.
This section describes how to use php to solve this problem.
$ Tres indicates a feasible attempt.
$ Res record summary result
For detailed data structure analysis, refer to the link.
$value){ if($key<$l){ if($value==$c){ return 0; }else if(abs($l-$key)==abs($c-$value)){ return 0; } } } return 1;}function scan($line){ global $tres; global $res; global $n,$count; if($line==$n){ $res[]=$tres; // $tres=array(); $count++; }else{ for($i=0;$i<$n;$i++){ if(check($line,$i)==1){ $tres[$line]=$i; $nxline=$line+1; scan($nxline); } } }}$tres=array();$res=array();$n=8;$count=0;$stime=microtime();scan(0);$etime=microtime();var_dump($res);echo there is $count ways !;$t=$etime-$stime;echo (int)$t.seconds used.;
// It should be noted that the final aspect of time calculation is not rigorous and the variable php with high precision cannot be directly subtracted, and there will be severe errors. This is only a temporary demonstration. You must call the relevant functions for exact calculation.