UNB/ CS/ David Bremner/ teaching/ cs3383/ lectures/ 50.1-demos/ nqueens.py
#!/usr/bin/env python3
def backtrack(P0):
    S = [P0]
    while len(S) > 0:
        P = S.pop()
        result = test(P)
        if result == True:
            return P
        elif result == None:
            for R in expand(P):
                S.append(R)
    return False

def test(Q):
  default = True
  for i in range(len(Q)):
    if Q[i]==None:
      default = None
    else:
      for j in range(i):
        if Q[i] - Q[j] in [0,i-j,j-i]:
          return False
  return default

def expand(Q):
  i=0; S=[]
  while Q[i] != None:
    i+=1
  for j in range(len(Q)):
    R=Q[:] # copy
    R[i] = j
    S.append(R)
  return S

if __name__ == "__main__":
    print(backtrack([None for _ in range(4)]))