-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
68 lines (57 loc) · 1.92 KB
/
main.py
File metadata and controls
68 lines (57 loc) · 1.92 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
"""
N-Queens Solution Generator
Ian S. Woodley
This is an expanded version of the classic '8-Queens' problem to
generate a solution for any passed integer. But really, don't try it
with numbers higher than 17. For your CPU's sake.
Note: Some passed integers will have no possible solution. Try in the range
4 <-> 17.
https://en.wikipedia.org/wiki/Eight_queens_puzzle
"""
# Function takes an integer value (n) and returns a 2D list
# containing a valid solution to the n-Queens problem (if possible).
def getSolution(n):
grid = [ ['_' for _ in range(n)] for _ in range(n) ]
used = set()
def sharesRow(x, y):
for dx, dy in used:
if y == dy and x != dx:
return True
return False
def sharesColumn(x, y):
for dx, dy in used:
if x == dx and y != dy:
return True
return False
def sharesDiagonal(x, y):
for dx, dy in used:
if abs(x - dx) == abs(y - dy):
return True
return False
def placeQueens(x=0):
for y in range(n):
if any( [ sharesRow(x, y), sharesColumn(x, y),
sharesDiagonal(x, y) ] ):
continue
used.add( (x, y) )
if x < n - 1 and not placeQueens(x + 1):
used.remove( (x, y) )
else:
return True
return False
# Execution
if not placeQueens():
return list("Solution not possible.")
for x, y in used:
grid[y][x] = 'Q'
return grid
if __name__ == "__main__":
while True:
uip = input("Pass a positive integer.")
if not uip.isdigit():
print("Invalid input.")
continue
solution = getSolution(int(uip))
print(*solution, sep='\n')
input("\nPress ENTER to exit.")
break