## 八皇后问题的python实现，附带输出图解 原

李艳青1987

bahuanghou.py

#!/usr/local/bin/python3.5 -u

def checkAvaliable(occupiedPoints, point):
for i in range(len(occupiedPoints)):
if occupiedPoints[i] == point or point - occupiedPoints[i] == len(occupiedPoints) - i or point - occupiedPoints[i] == i - len(occupiedPoints):
return(1)
return(0)

def func(num, avaliablePoints, occupiedPoints):
if len(occupiedPoints) == num:
global solutionNum
print("Solution " + str(solutionNum) + ":")
solutionNum = solutionNum + 1
for i in range(len(occupiedPoints)):
occupiedPoint = occupiedPoints[i]
print("+---"*num + "+")
print("+   "*occupiedPoint + "+ Q " + "+   "*(num-occupiedPoint-1) + "+")
print("+---"*num + "+")
print("")
return(0)
else:
if len(avaliablePoints) == 0:
return(1)
else:
for j in range(len(avaliablePoints)):
avaliablePoint = avaliablePoints[j]
if not checkAvaliable(occupiedPoints, avaliablePoint):
avaliablePointsTemp = avaliablePoints[:]
avaliablePointsTemp.remove(avaliablePoint)
occupiedPointsTemp = occupiedPoints[:]
occupiedPointsTemp.append(avaliablePoint)
func(num, avaliablePointsTemp, occupiedPointsTemp)

def main():
num = 8
avaliablePoints = list(range(num))
occupiedPoints = []
global solutionNum
solutionNum = 1
func(num, avaliablePoints, occupiedPoints)

###################
## Main Function ##
###################
if __name__ == "__main__":
main()

... ...

### 李艳青1987

2018/07/23
5
0
[codeup] 2046 八皇后

trav
02/08
0
0

yawn-silence
2018/03/04
677
0
DFS算法

DFS算法 三个经典例子 1 排列数 问题: 生成1~n的排列 思路: 一颗N层的树 每层节点为n^n个 在生成结果数组前把重复的去掉 DFS出口: 遍历到排列结果数组长度 DFS实现: 尝试安排数字给结果数组 ...

hakase
2016/10/27
130
0

03/07
0
0

CentOS 7系统增加swap

tlanyan
17分钟前
2
0

JAVA日知录
57分钟前
5
0
PHP运行时全局构造体

struct _php_core_globals { zend_bool magic_quotes_gpc; // 是否对输入的GET/POST/Cookie数据使用自动字符串转义。 zend_bool magic_quotes_runtime; //是否对运行时从外部资源产生的数据使...

58分钟前
4
0
webpack插件html-webpack-plugin

6
0

zhengchen1996

4
0