【算法总结-回溯法】回溯与八皇后
来源:互联网 发布:java能做什么 知乎 编辑:程序博客网 时间:2024/05/18 01:02
<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
- 【算法总结-回溯法】回溯与八皇后
- 八皇后与回溯法
- 八皇后与回溯法
- 回溯算法-八皇后
- 回溯算法-八皇后
- 回溯算法&八皇后
- 八皇后问题与回溯算法
- 八皇后问题与回溯算法
- 算法与数据结构-回溯法及八皇后问题求解
- 八皇后回溯法
- 回溯法, 八皇后
- 八皇后,回溯法
- 八皇后 回溯法
- 回溯法八皇后
- 回溯算法---八皇后问题
- 回溯算法-八皇后问题
- 八皇后问题回溯算法
- 回溯算法解八皇后
- wake on lan 实现远程开机(远程开关机程序)
- Creating a New ASM Disk Header After Existing One Is Corrupted
- 大数据时代来临 IT如何做好准备
- Lessons on development of 64-bit C/C++ applications(64位C/C++开发教程)
- OutputDebugString用法
- 【算法总结-回溯法】回溯与八皇后
- Android4.0新的SDK新特性 (转)
- Discuz!NT中集成Memcached分布式缓存
- CRgn几种创建方法,不规则窗体
- Android入门第八篇之GridView(九宫图)
- linux 下软件管理大全
- 视频13--学习心得--循环的嵌套(循环与循环,循环与选择结构)
- iPhone之NSString, char, NSData相互转化
- vc实现异形半透明窗体