#!/usr/bin/env python # USACH - nov 2012 - c.durr # depth first search for the n-queen problem # with forward check and arc-consistancy import sys n = int(sys.argv[1]) # the n-queen instance Vars = range(n) Vals = range(n) # the actual constraint: is assigning queen x to u and queen y to v not conflicting? def isValid(x,u, y,v): return u!=v and u+x-y!=v and u-x+y!=v # domain of variables. Read only the first size[x] values, the rest are deleted values dom = [[u for u in Vals] for x in Vals] size = [n for x in Vals] # loop over domain of x def domain(x): for i in range(size[x]): yield dom[x][i] # context history hst = [] def saveContext(): global size, hst hst.append(size[:]) def restoreContext(): global size, hst size = hst.pop() # remove i-th value of domain of x def removeVal(x,i): global size size[x]-=1 dom[x][i], dom[x][size[x]] = dom[x][size[x]], dom[x][i] # returns set of variables which domain got reduced def forwardCheck(x): Q = set() u = val[x] for y in Vars: if y!=x and val[y]==None: i=0 while i