八皇后问题(Python实现)

看《Python基础教程》,看到生成器一章,提到八皇后问题,没有继续往后看,自己试着写了一个。

八皇后问题是数据结构里面的经典问题,思路主要是利用回溯法,利用栈保留走过的路径,走过的路,入栈,走不通了,出栈,继续往下尝试。

思路比较简单,写个伪码没什么问题。但是写得时间比较长,要是面试的时候让你笔写个无BUG可运行版本,那还真得喊救命了


运行结果:能够打印出全部92种解法,只是判断冲突的办法,太low了...................


#encoding:utf-8
import copy
def checkAttack(array):

	for i in range(len(array)):
		x=sum(array[i])
		check="水平"+str(x)
		if (x>1):
			print check
			return True

	for i in range(len(array)):
		x=[]
		for j in range(len(array)):
			x.append(array[j][i])
		y=sum(x)
		check="竖直"+str(y)
		if(y>1):
			print check
			return True


	for  i in range(len(array)):
		x=[]
		p=[]
		j=i
		k=0
		while j>=0 and k<=i:
			x.append(array[j][k])
			p.append(array[len(array)-1-k][len(array)-1-j])
			j-=1
			k+=1
		y=sum(x)
		q=sum(p)
		check="左对"+str((y,q))
		if y>1 or q>1:
			print check
			return True

	
	for  i in range(len(array)-1,-1,-1):
		x=[]
		p=[]
		j=i
		k=0
		while j<=len(array)-1:
			x.append(array[k][j])
			p.append(array[j][k])
			j+=1
			k+=1
		y=sum(x)
		q=sum(p)
		check="右对"+str((y,q))
		if y>1 or q>1:
			print check
			return True

	return False


def initBorad():
	board=[];
	for _ in range(8):
		x=map( lambda x:x-x,range(8) )
		board.append(x)
	return board



def eightQueen():
	board=initBorad()
	allBoard=[]
	stack=[]
	i=j=0
	try:
		while True:
			while  i < len(board):
				print (i,j)
				found=False
				while j < len(board):
					board[i][j]=1
					if (checkAttack(board)==True):
						board[i][j]=0
						j+=1
					else:
						stack.append((i,j))
						print "in stack"+str((i,j))
						found=True
						i+=1
						j=0
						break
				if found==False:
					i,j=stack.pop()
					board[i][j]=0
					print "out stack"+str((i,j)) 
					j+=1
			for xp in board:
				print xp
			allBoard.append(board)
			print "目前找到:"+str(len(allBoard))
			x=copy.deepcopy(board)
			board=x
			i,j=stack.pop()
			board[i][j]=0
			j+=1
	except (Exception) as e:
		print e
		return allBoard


x=eightQueen()


count=0

for ie in x:
	count+=1
	print "\n解法:"+str(count)
	for ii in ie:
		print ii


你可能感兴趣的:(Python,基础算法)