八皇后 - 结果去重
程序员文章站
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))
推荐阅读
-
Oracle列转行函数Listagg()查询结果的去重(去除重复值)的方法详解
-
【剑指Offer】字符串的排序(全排列,结果是否去重可以考虑用list还是set)
-
当初去花果山捉拿孙悟空,如果派猪八戒去结果会怎样
-
[学习笔记] Oracle运算符、连接符、结果去重、范围查询、模糊查询
-
Oracle列转行函数Listagg()查询结果的去重(去除重复值)的方法详解
-
八皇后 - 结果去重
-
mysql count distinct 统计结果去重
-
mysql count distinct 统计结果去重
-
[学习笔记] Oracle运算符、连接符、结果去重、范围查询、模糊查询
-
【MySQL】十三、关于查询结果的去重(distinct)