利用python实现八皇后问题,输出图解。
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()
输出图解:
... ...
可变更程序中的“n = 8”来实现n皇后问题,随着n的增大,解决方案数目也会急剧增加。