php 實現八皇后問題

來源:互聯網
上載者:User

標籤:blog   io   ar   for   on   div   問題   log   cti   

php實現的八皇后問題,可以推廣到N皇后

<?php class Empress{private $queen;//儲存位置,例如$queen[2] = 3表示第三行的第四列位置,行列從0計數public static $count;//總共有多少種排列順序 private $m;//規模數量//設定幾皇后,返回排列結果public function getResult($m){$this->m = $m;$this->put(0);}//判斷第$n行置放位置$queen[$n] = $i 是否和前面的行衝突(同行,同列衝突,對角線衝突)/** * @param $n 第n行 * @return  bool是否衝突 */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;}/** *  * 列印函數 */private function show(){for ($i=0;$i<$this->m;$i++){echo $this->queen[$i].‘--‘;}}/** *  * 放置第n行的位置 */private function put($n){for ($i=0;$i<$this->m;$i++){$this->queen[$n] = $i;//依次試探$tmp_res = $this->attack($n);//如果沒有衝突,要麼繼續放置下一行,要麼到最後一行了。if(!$tmp_res){if($n==$this->m-1){$this->show();echo ‘第‘.(self::$count+1).‘種排列方法‘;echo "<br/>";self::$count++;}else{$this->put($n+1);}}}}}class Client{public static function main(){$obj = new Empress();$obj->getResult(4);}}Client::main();?>

  

php 實現八皇后問題

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.