Skip to content

Commit 316d5ff

Browse files
DaveAxiompoyea
authored andcommitted
Add NQueens backtracking search implementation (TheAlgorithms#504)
1 parent f5abc04 commit 316d5ff

File tree

1 file changed

+77
-0
lines changed

1 file changed

+77
-0
lines changed

other/nqueens.py

+77
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,77 @@
1+
#! /usr/bin/python3
2+
import sys
3+
4+
def nqueens(board_width):
5+
board = [0]
6+
current_row = 0
7+
while True:
8+
conflict = False
9+
10+
for review_index in range(0, current_row):
11+
left = board[review_index] - (current_row - review_index)
12+
right = board[review_index] + (current_row - review_index);
13+
if (board[current_row] == board[review_index] or (left >= 0 and left == board[current_row]) or (right < board_width and right == board[current_row])):
14+
conflict = True;
15+
break
16+
17+
if (current_row == 0 and conflict == False):
18+
board.append(0)
19+
current_row = 1
20+
continue
21+
22+
if (conflict == True):
23+
board[current_row] += 1
24+
25+
if (current_row == 0 and board[current_row] == board_width):
26+
print("No solution exists for specificed board size.")
27+
return None
28+
29+
while True:
30+
if (board[current_row] == board_width):
31+
board[current_row] = 0
32+
if (current_row == 0):
33+
print("No solution exists for specificed board size.")
34+
return None
35+
36+
board.pop()
37+
current_row -= 1
38+
board[current_row] += 1
39+
40+
if board[current_row] != board_width:
41+
break
42+
else:
43+
current_row += 1
44+
if (current_row == board_width):
45+
break
46+
47+
board.append(0)
48+
return board
49+
50+
def print_board(board):
51+
if (board == None):
52+
return
53+
54+
board_width = len(board)
55+
for row in range(board_width):
56+
line_print = []
57+
for column in range(board_width):
58+
if column == board[row]:
59+
line_print.append("Q")
60+
else:
61+
line_print.append(".")
62+
print(line_print)
63+
64+
65+
if __name__ == '__main__':
66+
default_width = 8
67+
for arg in sys.argv:
68+
if (arg.isdecimal() and int(arg) > 3):
69+
default_width = int(arg)
70+
break
71+
72+
if (default_width == 8):
73+
print("Running algorithm with board size of 8. Specify an alternative Chess board size for N-Queens as a command line argument.")
74+
75+
board = nqueens(default_width)
76+
print(board)
77+
print_board(board)

0 commit comments

Comments
 (0)