欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

八皇后 - 结果去重

程序员文章站 2022-05-25 11:53:44
...

去重后的结果,虽然显示两个,但是其实是等价的,主要就是对称性。如果继续去重,感觉可以将XY对调再去重。不再做调整了。


def TwinsQuickSort(datalist):
	if len(datalist)<=1:
		return datalist
	pivot=datalist[0]
	left=[];right=[];
	for i in range(len(datalist)):
		if i==0:
			continue;
		else:
			if datalist[i][0]<pivot[0]:				
				left.append(datalist[i])
			else:
				if datalist[i][0]>pivot[0]:
					right.append(datalist[i])
				else:
					if datalist[i][1]<pivot[1]:
						left.append(datalist[i])
					else:
						right.append(datalist[i])	
					
	return TwinsQuickSort(left) + [pivot] + TwinsQuickSort(right)

def QuickSort(datalist):
	if len(datalist)<=1:
		return datalist
	pivot=datalist[0]
	left=[];right=[];
	for i in range(len(datalist)):
		if i==0:
			continue;
		else:
			if datalist[i]<pivot:
				left.append(datalist[i])
			else:
				right.append(datalist[i])

	return QuickSort(left) + [pivot] + (QuickSort(right))





import sys,copy

#Queens -- 
def checkPlaceOK(queens, curPlace,maxrow):
	if len(queens)<=0:
		return True
	if ( curPlace[0]>=maxrow or curPlace[1]>=maxrow):
		return False
	for q in queens:
		if ( curPlace[0]==q[0] or curPlace[1]==q[1] ):
			return False
		if ( (q[1]-q[0])==(curPlace[1]-curPlace[0]) or q[0]+q[1]==curPlace[0]+curPlace[1]):
			return False
	return True



def findNxtQueenPlace(queens,startplace,maxrow):
	isok=False
	i,j=startplace[0],startplace[1]
	while i<maxrow:
		while j<maxrow:
			if checkPlaceOK(queens,(i,j),maxrow):
				isok=True; break;
			else:
				j=j+1
		if isok:
			break
		else:
			i=i+1;j=0;

	if isok:
		return True,(i,j)		
	return False,(-1,-1)


def updateLastQueenPlace(queens,maxrow):
	exit=False
	if len(queens)<=0:
		print "Queen is empty, will exit"
		return


	lastqueen=queens[len(queens)-1]
	del queens[len(queens)-1]
	isok,place=findNxtQueenPlace(queens,(lastqueen[0],lastqueen[1]+1),maxrow)
	if isok:
		queens.append(place)
		return
	else:
		updateLastQueenPlace(queens,maxrow)


solutions=[]
queens=[(0,0)]
MAXROW=4
while(queens[0][0]<MAXROW):
	while len(queens)<MAXROW:
		if len(queens)<=0:
			break

		find,nxtPlace=findNxtQueenPlace(queens,(0,0),MAXROW)
		if find:
			queens.append(nxtPlace)
		else:
			updateLastQueenPlace(queens,MAXROW)

		if len(queens)>=MAXROW:	
			result=copy.deepcopy(queens)		 
			solutions.append(result) #Find one solution
			# find next solution
			del queens[len(queens)-1]
			updateLastQueenPlace(queens,MAXROW)

	if len(queens)<=0:
		break 

sortresult=[]
for i in range(len(solutions)):
	sortresult.append(str(TwinsQuickSort(solutions[i])))
	print "Solution ",i,": ",sortresult[i]

print sortresult

removeDup=set(sortresult)
print (list(removeDup))

 

 

八皇后 - 结果去重

八皇后 - 结果去重 

相关标签: 八皇后 python