Python学习之 八皇后

把皇后这个经典的问题早就听说过 但是一直没自己去实现过 这次学习Python的时候用Pyhon实现了一下 代码是来自看的书上的

def conflict(state,nextX):
	nextY=len(state)
	for i in range(nextY):
		if abs(state[i]-nextX) in (0,nextY):
			return True
	return False

def 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,)+result
				
def prettyprint(solution):
	def line(pos,lengh=len(solution)):
		return '.'*(pos)+'X'+'.'*(lengh-pos-1)
	for pos in solution:
		print(line(pos))

import random
prettyprint(random.choice(list(queens(8))))

  

posted @ 2011-09-16 23:25  Crazy_yiner  阅读(613)  评论(0编辑  收藏  举报