PHP implementation of the eight Queen problem can be extended to the N queen
<?php class empress{private $queen;//storage location, for example $queen[2] = 3 for the fourth column of the third row, the rows and columns from 0 public static $count;//Total number of permutations private $m;//number of sizes//setting a few queens, returning the arrangement result public function GetResult ($m) {$this->m = $m; $this->put (0);} Determine $n position $queen[$n] = $i If the previous row conflict (peer, same column conflict, diagonal conflict)/** * @param $n nth row * @return bool conflict */private function Attack ($n) { for ($i =0; $i < $n; $i + +) {if ($this->queen[$n] = = $this->queen[$i] | | ABS ($this->queen[$n-$this->queen[$i]) = = ABS ($n-$i)) {return true;}} return false;} /** * * Print functions */private function Show () {for ($i =0; $i < $this->m; $i + +) {echo $this->queen[$i]. ' --‘;}} /** * * Place nth row position */private function put ($n) {for ($i =0; $i < $this->m; $i + +) {$this->queen[$n] = $i;//Test $tmp_res = $ This->attack ($n);//If there is no conflict, either continue to place the next line or go to the last line. if (! $tmp _res) {if ($n = = $this->m-1) {$this->show (); Echo ' first '. ( Self:: $count + 1). ' The method of arrangement '; Echo ' <br/>; Self:: $count + +;} else{$this->put ($n + 1);}}}} Class Client{public static function main () {$obj = new Empress (); $obj->getresulT (4);}} Client::main ();? >
PHP implementation eight Queen problem