-
Notifications
You must be signed in to change notification settings - Fork 0
/
n_queens.py
executable file
·76 lines (40 loc) · 1.73 KB
/
n_queens.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
import psycopg2
from itertools import permutations
from sqlalchemy.engine import create_engine
from mixins import BacktrackingMixin
from models import Solution
class NQueens(BacktrackingMixin):
"""
Creates an object with the amount of queens, and its respective solutions. The solution was borrowed from this author https://goo.gl/xd1bj1 and refactorized with OOP.
Inherits from BacktrackingMixing that allows using backtracking algorithm. It was done just for illustration matters of DRY principles.
"""
def __init__(self, size, type):
"""
size = Integer
type = Integer
"""
self.size = size
self.type = type
self.solutions_count = 0
self.solutions = []
if self.type == 1:
self.solve_brute_force()
elif self.type == 2:
self.solutions = self.solve_backtracking(self.size)
self.solutions_count = len(self.solutions)
def solve_brute_force(self):
cols = range(self.size)
for positions in permutations(cols):
positive_diagonal = set(positions[i]+i for i in cols)
negative_diagonal = set(positions[i]-i for i in cols)
if self.size == len(positive_diagonal) == len(negative_diagonal):
self.solutions_count += 1
self.solutions.append(positions)
return self.solutions
def print_solutions(self):
N=self.size
solutions = self.solutions
for solution in solutions:
sol = solutions.index(solution) + 1
print('Solution {}: {} \n'.format(sol, solution))
print("\n".join(' o ' * i + ' X ' + ' o ' * (N-i-1) for i in solution) + "\n\n")