5 The (well-known) problem is due to Niklaus Wirth.
7 This solution is inspired by Dijkstra (Structured Programming). It is
8 a classic recursive backtracking approach.
12 N
= 8 # Default; command line overrides
16 def __init__(self
, n
=N
):
22 self
.y
= [None] * n
# Where is the queen in column x
23 self
.row
= [0] * n
# Is row[y] safe?
24 self
.up
= [0] * (2*n
-1) # Is upward diagonal[x-y] safe?
25 self
.down
= [0] * (2*n
-1) # Is downward diagonal[x+y] safe?
26 self
.nfound
= 0 # Instrumentation
28 def solve(self
, x
=0): # Recursive solver
29 for y
in range(self
.n
):
39 return not self
.row
[y
] and not self
.up
[x
-y
] and not self
.down
[x
+y
]
41 def place(self
, x
, y
):
47 def remove(self
, x
, y
):
53 silent
= 0 # If true, count solutions only
56 self
.nfound
= self
.nfound
+ 1
59 print '+-' + '--'*self
.n
+ '+'
60 for y
in range(self
.n
-1, -1, -1):
62 for x
in range(self
.n
):
68 print '+-' + '--'*self
.n
+ '+'
74 if sys
.argv
[1:2] == ['-n']:
82 print "Found", q
.nfound
, "solutions."
84 if __name__
== "__main__":