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‎

Lines changed: 77 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,77 @@
1+
#! /usr/bin/python3
2+
importsys
3+
4+
defnqueens(board_width):
5+
board= [0]
6+
current_row=0
7+
whileTrue:
8+
conflict=False
9+
10+
forreview_indexinrange(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>=0andleft==board[current_row]) or (right<board_widthandright==board[current_row])):
14+
conflict=True;
15+
break
16+
17+
if (current_row==0andconflict==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==0andboard[current_row] ==board_width):
26+
print("No solution exists for specificed board size.")
27+
returnNone
28+
29+
whileTrue:
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+
returnNone
35+
36+
board.pop()
37+
current_row-=1
38+
board[current_row] +=1
39+
40+
ifboard[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+
returnboard
49+
50+
defprint_board(board):
51+
if (board==None):
52+
return
53+
54+
board_width=len(board)
55+
forrowinrange(board_width):
56+
line_print= []
57+
forcolumninrange(board_width):
58+
ifcolumn==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+
forarginsys.argv:
68+
if (arg.isdecimal() andint(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)