Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content

Add NQueens backtracking search implementation #504

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
May 19, 2019
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
77 changes: 77 additions & 0 deletions other/nqueens.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
#! /usr/bin/python3
import sys

def nqueens(board_width):
board = [0]
current_row = 0
while True:
conflict = False

for review_index in range(0, current_row):
left = board[review_index] - (current_row - review_index)
right = board[review_index] + (current_row - review_index);
if (board[current_row] == board[review_index] or (left >= 0 and left == board[current_row]) or (right < board_width and right == board[current_row])):
conflict = True;
break

if (current_row == 0 and conflict == False):
board.append(0)
current_row = 1
continue

if (conflict == True):
board[current_row] += 1

if (current_row == 0 and board[current_row] == board_width):
print("No solution exists for specificed board size.")
return None

while True:
if (board[current_row] == board_width):
board[current_row] = 0
if (current_row == 0):
print("No solution exists for specificed board size.")
return None

board.pop()
current_row -= 1
board[current_row] += 1

if board[current_row] != board_width:
break
else:
current_row += 1
if (current_row == board_width):
break

board.append(0)
return board

def print_board(board):
if (board == None):
return

board_width = len(board)
for row in range(board_width):
line_print = []
for column in range(board_width):
if column == board[row]:
line_print.append("Q")
else:
line_print.append(".")
print(line_print)


if __name__ == '__main__':
default_width = 8
for arg in sys.argv:
if (arg.isdecimal() and int(arg) > 3):
default_width = int(arg)
break

if (default_width == 8):
print("Running algorithm with board size of 8. Specify an alternative Chess board size for N-Queens as a command line argument.")

board = nqueens(default_width)
print(board)
print_board(board)