经典回溯算法之八皇后问题 -- Python
2018-03-06 23:17
375 查看
# -*- coding: UTF-8 -*- import copy # 使用全局变量保存结果 global arr global count global mlist # 定义条件判定函数 def conflict(index,col): global arr for i in range(index): if arr[i][col] == 1: return True for j in range(8): if arr[i][j] == 1 and abs(i-index) == abs(j-col): return True return False # 递归查找函数 def find(index): global count, arr,mlist if index == 8: # 结束条件 count += 1 mlist.append(copy.deepcopy(arr)) else: for i in range(8): # 穷举所有可能 if not conflict(index,i): arr[index][i] = 1 # 设置当前完成步骤 find(index+1) # 继续探索剩余步骤 arr[index][i] = 0 # 恢复原貌 if __name__ == "__main__": global count,arr # 初始化 arr = [[0]*8 for i in range(8)] # 棋盘 count = 0 mlist = [] find(0) # 开始计算 # 打印结果 print(count) for k in range(count): print("-----------------------------") for i in range(8): print(mlist[k][i])
相关文章推荐
- Python实现八皇后问题
- 八皇后问题 - Python - from Python基础教程
- 17. Python脚本学习笔记十七Python的八皇后问题
- 流动python - 八皇后问题简单解决方案
- 利用python的生成器解决八皇后问题
- 【算法】八皇后问题 Python实现
- Python求解“八皇后”问题的递归思路
- Python版的八皇后问题
- 八皇后问题 Python 版
- 八皇后问题的进化(4)-python写的八皇后
- python基础教程总结8——特殊方法,属性,迭代器,生成器,八皇后问题
- python实现八皇后问题
- 小白教学式,八皇后问题,Python生成器解法
- 八皇后问题的python代码
- Python解决八皇后问题示例
- Python计算八皇后问题
- Python中的生成器在八皇后问题上的应用
- python 解决八皇后问题
- 八皇后问题之python和scheme实现
- Python之八皇后问题