上一篇有两个问题:
1)只能得到一个可能的解,不是所有的;
2)虽然得到的解是正确的,但是逻辑上有个小bug,
3)这次是给出了所有解,但还未做去重处理,下一篇将添加去重处理
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
for i in range(len(solutions)):
print "Solution ",i,": ",solutions[i]
运行结果: