import random
from random import choice
import sys
def findConflicts(board, queen):
n = len(board)
conflicts = 0
# W
for i in range(0,queen):
if(board[i] == board[queen]):
conflicts += 1
break
# E
for i in range(queen+1, n):
if(board[i] == board[queen]):
conflicts += 1
break
# NW
for i in range(0,queen):
if(board[i] == board[queen] + queen - i):
conflicts += 1
break
# SW
for i in range(0,queen):
if(board[i] == board[queen] - queen + i):
conflicts += 1
break
# NE
for i in range(queen+1, n):
if(board[i] == board[queen] - queen + i):
conflicts += 1
break
# SE
for i in range(queen+1, n):
if(board[i] == board[queen] + queen - i):
conflicts += 1
break
return conflicts
def checkBoard(board):
for i in range(0, len(board)):
if(findConflicts(board, i) > 0):
return False
return True
def solveBoard(board):
colNames = ['a','b','c','d','e','f','g','h']
steps = 10000
moves = 0
lastMoved = None
for i in range(0, steps):
if(checkBoard(board) == True):
print "moves: "+str(moves)
return board
randQueen = random.randint(0, len(board)-1)
currentConflicts = findConflicts(board, randQueen)
if(currentConflicts > 0 and randQueen != lastMoved):
colConflicts = []
for row in range(1, len(board)+1):
testBoard = list(board)
testBoard[randQueen] = row
colConflicts.append(findConflicts(testBoard, randQueen))
minConflict = min(colConflicts)
minConflictRows = [t for t, u in enumerate(colConflicts) if u == minConflict]
newRow = choice(minConflictRows)+1
if(board[randQueen] != newRow):
print colNames[randQueen]+str(board[randQueen])+" -> "+colNames[randQueen]+str(newRow)
board[randQueen] = newRow
lastMoved = randQueen
moves += 1
return None
if(len(sys.argv) >= 2):
board = [int(x) for x in sys.argv[1].split(",")]
else:
print "missing board argument"
sys.exit(0)
colNames = ['a','b','c','d','e','f','g','h']
boardToSolve = list(board)
for i in range(len(boardToSolve)):
boardToSolve[i] = colNames[i]+str(boardToSolve[i])
print ",".join([str(n) for n in boardToSolve])
board = solveBoard(board)
if(board is None):
print "Solution not found"
else:
for i in range(len(board)):
board[i] = colNames[i]+str(board[i])
print ",".join([str(n) for n in board])