-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathn_queens.py
66 lines (59 loc) · 1.85 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
66
from queue import Queue
class NQueens:
def __init__(self, size):
self.size = size
def solve_dfs(self):
if self.size < 1:
return []
solutions = []
stack = [[]]
while stack:
solution = stack.pop()
if self.conflict(solution):
continue
row = len(solution)
if row == self.size:
solutions.append(solution)
continue
for col in range(self.size):
queen = (row, col)
queens = solution.copy()
queens.append(queen)
stack.append(queens)
return solutions
def solve_bfs(self):
if self.size < 1:
return []
solutions = []
queue = Queue()
queue.put([])
while not queue.empty():
solution = queue.get()
if self.conflict(solution):
continue
row = len(solution)
if row == self.size:
solutions.append(solution)
continue
for col in range(self.size):
queen = (row, col)
queens = solution.copy()
queens.append(queen)
queue.put(queens)
return solutions
def conflict(self, queens):
for i in range(1, len(queens)):
for j in range(0, i):
a, b = queens[i]
c, d = queens[j]
if a == c or b == d or abs(a - c) == abs(b - d):
return True
return False
def print(self, queens):
for i in range(self.size):
print(' ---' * self.size)
for j in range(self.size):
p = 'Q' if (i, j) in queens else ' '
print('| %s ' % p, end='')
print('|')
print(' ---' * self.size)