PHP implementation eight Queen problem

Source: Internet
Author: User
Tags abs php class

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.