|
| 1 | +#!/usr/bin/env python3 |
| 2 | + |
| 3 | +from __future__ import print_function |
| 4 | + |
| 5 | +""" |
| 6 | +N queens problem. |
| 7 | +
|
| 8 | +The (well-known) problem is due to Niklaus Wirth. |
| 9 | +
|
| 10 | +This solution is inspired by Dijkstra (Structured Programming). It is |
| 11 | +a classic recursive backtracking approach. |
| 12 | +""" |
| 13 | + |
| 14 | +N = 8 # Default; command line overrides |
| 15 | + |
| 16 | +class Queens: |
| 17 | + |
| 18 | + def __init__(self, n=N): |
| 19 | + self.n = n |
| 20 | + self.reset() |
| 21 | + |
| 22 | + def reset(self): |
| 23 | + n = self.n |
| 24 | + self.y = [None] * n # Where is the queen in column x |
| 25 | + self.row = [0] * n # Is row[y] safe? |
| 26 | + self.up = [0] * (2*n-1) # Is upward diagonal[x-y] safe? |
| 27 | + self.down = [0] * (2*n-1) # Is downward diagonal[x+y] safe? |
| 28 | + self.nfound = 0 # Instrumentation |
| 29 | + |
| 30 | + def solve(self, x=0): # Recursive solver |
| 31 | + for y in range(self.n): |
| 32 | + if self.safe(x, y): |
| 33 | + self.place(x, y) |
| 34 | + if x+1 == self.n: |
| 35 | + self.display() |
| 36 | + else: |
| 37 | + self.solve(x+1) |
| 38 | + self.remove(x, y) |
| 39 | + |
| 40 | + def safe(self, x, y): |
| 41 | + return not self.row[y] and not self.up[x-y] and not self.down[x+y] |
| 42 | + |
| 43 | + def place(self, x, y): |
| 44 | + self.y[x] = y |
| 45 | + self.row[y] = 1 |
| 46 | + self.up[x-y] = 1 |
| 47 | + self.down[x+y] = 1 |
| 48 | + |
| 49 | + def remove(self, x, y): |
| 50 | + self.y[x] = None |
| 51 | + self.row[y] = 0 |
| 52 | + self.up[x-y] = 0 |
| 53 | + self.down[x+y] = 0 |
| 54 | + |
| 55 | + silent = 0 # If true, count solutions only |
| 56 | + |
| 57 | + def display(self): |
| 58 | + self.nfound = self.nfound + 1 |
| 59 | + if self.silent: |
| 60 | + return |
| 61 | + print('+-' + '--'*self.n + '+') |
| 62 | + for y in range(self.n-1, -1, -1): |
| 63 | + print('|', end=' ') |
| 64 | + for x in range(self.n): |
| 65 | + if self.y[x] == y: |
| 66 | + print("Q", end=' ') |
| 67 | + else: |
| 68 | + print(".", end=' ') |
| 69 | + print('|') |
| 70 | + print('+-' + '--'*self.n + '+') |
| 71 | + |
| 72 | +def main(): |
| 73 | + import sys |
| 74 | + silent = 0 |
| 75 | + n = N |
| 76 | + if sys.argv[1:2] == ['-n']: |
| 77 | + silent = 1 |
| 78 | + del sys.argv[1] |
| 79 | + if sys.argv[1:]: |
| 80 | + n = int(sys.argv[1]) |
| 81 | + q = Queens(n) |
| 82 | + q.silent = silent |
| 83 | + q.solve() |
| 84 | + print("Found", q.nfound, "solutions.") |
| 85 | + |
| 86 | +if __name__ == "__main__": |
| 87 | + main() |
0 commit comments