【演算法總結-回溯法】回溯與八皇后

來源:互聯網
上載者:User
<html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><title> test </title></head><body> <div><?php     /*八皇后問題代碼實現      *      *      *      *///根據前幾行的放置情況,判斷這一行是否合法function attack($n){    global $chess;    for($i=1;$i<=$n-1;$i++){       if($chess[$n]==$chess[$i]+($n-$i)||$chess[$n]==$chess[$i]-($n-$i)||$chess[$n]==$chess[$i]){          return true;       }       }     return false;}//輸出每種可能的解function display(){     global $chess;    global $solution;    echo "    solution".sprintf("% 2d",$solution).":";    for($i=1;$i<=8;$i++){       $img = "<img src='../images/$chess[$i].png'/>";       echo $img;     }    echo "</br>";     $solution++;  }//遞迴放置皇后function putchess($n){      global $chess;    global $solution;    for($i=1;$i<=8;$i++){        $chess[$n] =$i;        if(!attack($n)){//沒有衝突           if($n==8){//已經放滿,輸出               display();   }           else{                              putchess($n+1);                     }                     }//if                 }//for                                }printf("八皇后問題的解如下:<br/>");$solution = 1;//$chess=array(1,2,3,4,5,6,7,8);putchess(1);echo "共有".($solution-1)."種不同的八皇后放置方法";           ?></div></body></html>

python版本的解法如下:

def conflict(state,nextX):    nextY = len(state)    for i in range(nextY):        if(abs(state[i]-nextX)) in (0,nextY-i):            return True    return Falsedef queens(num = 8,state = ()):        for pos in range(num):        if not conflict(state,pos):            if len(state) == num-1:                yield (pos,)            else:                for result in queens(num,state+(pos,)):                    yield (pos,)+resultdef prettyprint(solution):    def line(pos,length = len(solution)):        return '. '*(pos) +'X '+'. '*(length-pos-1)    for pos in solution:        print line(pos)import randomprettyprint(random.choice(list(queens(8))))print len(list(queens(8))) 

結果:

. . X . . . . . . . . . X . . . . . . . . . X . X . . . . . . . . . . X . . . . . X . . . . . . . . . . . . . X . . . . . X . . 92

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.