I am developing an N-Queen Simulation using pygame.
class NQ:
def __init__(self,n):
self.size = n
self.columns = [] * self.size
self.places = 0
self.backtracks = 0
def place(self, startRow=0):
if len(self.columns) == self.size:
return self.columns
else:
for row in range(startRow, self.size):
if self.isSafe(len(self.columns), row) is True:
self.columns.append(row)
self.places += 1
return self.place()
else:
lastRow = self.columns.pop()
self.backtracks += 1
return self.place(startRow=lastRow + 1)
def isSafe(self, col, row):
for threatRow in self.columns:
threatCol = self.columns.index(threatRow)
if row == threatRow or col == self.columns.index(threatRow):
return False
elif threatRow + threatCol == row + col or threatRow - threatCol == row - col:
return False
return True
def process(n):
nqueens = NQ(n)
nqueens.place(0)
return nqueens.columns
Also I have a pygame procedure in another file to draw chess board which takes a list as input and place them accordingly.
If I want to show the movement of queens, how can i pass the list dynamically from the recursivecode procedure so that the exact backtracking procedure is visible.
Thank you
解决方案
If you want to know what is going on inside recursive function you can add external function as argument and than you can use it inside recursion to print current state of algorythm or draw queens on chess board.
In example I use show_colums() to print self.columns every time self.place() is running.
file: nq.py
class NQ:
def __init__(self,n, callback): # added callback
self.size = n
self.columns = []
self.places = 0
self.backtracks = 0
self.callback = callback # added callback
def place(self, startRow=0):
self.callback(self.columns) # added callback
if len(self.columns) == self.size:
return self.columns
else:
for row in range(startRow, self.size):
if self.isSafe(len(self.columns), row) is True:
self.columns.append(row)
self.places += 1
return self.place()
else:
lastRow = self.columns.pop()
self.backtracks += 1
return self.place(startRow=lastRow + 1)
def isSafe(self, col, row):
for threatRow in self.columns:
threatCol = self.columns.index(threatRow)
if row == threatRow or col == self.columns.index(threatRow):
return False
elif threatRow + threatCol == row + col or threatRow - threatCol == row - col:
return False
return True
file: main.py
from nq inport NQ
def show_columns(x):
print "columns:", x
def process(n):
nqueens = NQ(n, show_columns)
nqueens.place(0)
return nqueens.columns
process(8)
part of result
columns: []
columns: [0]
columns: [0, 2]
columns: [0, 2, 4]
columns: [0, 2, 4, 1]
columns: [0, 2, 4, 1, 3]
columns: [0, 2, 4, 1]
columns: [0, 2, 4, 1, 7]
columns: [0, 2, 4, 1]