-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathn_queen_problem.py
71 lines (51 loc) · 1.77 KB
/
n_queen_problem.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
67
68
69
70
71
"""Program to print all N-Queen Solutions in N * N board."""
QUEEN = "\u265B" # unicode of chess queen-symbol
N = 8
x = 1
def is_safe(board, row, col):
"""Checking if a queen can be placed on board[row][col]."""
# Check this row on left size
for i in range(col):
if board[row][i] == QUEEN:
return False
# Check upper diagonal on left side
for i, j in zip(range(row, -1, -1), range(col, -1, -1)):
if board[i][j] == QUEEN:
return False
# Check lower diagonal on left size
for i, j in zip(range(row, N, 1), range(col, -1, -1)):
if board[i][j] == QUEEN:
return False
return True
def n_queen_solution(board, col):
"""Function that return the solution if there any."""
res = False
global x
if col >= N:
print(x, ": ")
for i in range(N):
for j in range(N):
print(board[i][j], end=" ")
print()
print()
x += 1
return True
for i in range(N):
if is_safe(board, i, col):
board[i][col] = QUEEN
# if only one solution needed then use this block instead of next line.
# Also return False in last line in place of return res.
# >>
# if n_queen_solution(board, col + 1, n):
# return True
res = n_queen_solution(board, col + 1) or res
board[i][col] = '_' # backtrack
return res
def n_queen():
"""Program that print solution if exist."""
board = [['_' for _ in range(N)] for _ in range(N)]
y = n_queen_solution(board, 0)
if not y:
print("No solution exist!")
if __name__ == '__main__':
n_queen()