forked from MTrajK/coding-problems
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathqueens_problem.py
More file actions
100 lines (74 loc) · 1.99 KB
/
queens_problem.py
File metadata and controls
100 lines (74 loc) · 1.99 KB
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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
'''
Queens Problem
You have an N by N board. Write a function that, given N, returns the number of possible arrangements
of the board where N queens can be placed on the board without threatening each other,
i.e. no two queens share the same row, column, or diagonal.
=========================================
Backtracking solution.
Time Complexity: O(N!) (but I think it's much faster!)
Space Complexity: O(N)
* There are much faster solutions, like O(N^2)
'''
############
# Solution #
############
def place_n_queens(n):
columns = [False for i in range(n)]
order = []
return backtracking(columns, order)
def backtracking(columns, order):
# columns and order are references, no extra memory for those arrays (they are just pointers)
n = len(columns)
if len(order) == n:
return 1
total = 0
for i in range(n):
if (not columns[i]) and check_diagonals(order, i):
order.append(i)
columns[i] = True
total += backtracking(columns, order)
# return to the old state
columns[i] = False
del order[-1]
return total
def check_diagonals(order, pos):
current_row = len(order)
for i in range(current_row):
if (i - order[i]) == (current_row - pos):
return False
if (i + order[i]) == (current_row + pos):
return False
return True
###########
# Testing #
###########
# Test 1
# Correct result => 1
print(place_n_queens(1))
# Test 2
# Correct result => 0
print(place_n_queens(2))
# Test 3
# Correct result => 0
print(place_n_queens(3))
# Test 4
# Correct result => 2
print(place_n_queens(4))
# Test 5
# Correct result => 10
print(place_n_queens(5))
# Test 6
# Correct result => 4
print(place_n_queens(6))
# Test 7
# Correct result => 40
print(place_n_queens(7))
# Test 8
# Correct result => 92
print(place_n_queens(8))
# Test 9
# Correct result => 352
print(place_n_queens(9))
# Test 10
# Correct result => 724
print(place_n_queens(10))