8 queens problem solver


SUBMITTED BY: Guest

DATE: Dec. 31, 2013, 10 a.m.

FORMAT: Python

SIZE: 2.7 kB

HITS: 1151

  1. import random
  2. from random import choice
  3. import sys
  4. def findConflicts(board, queen):
  5. n = len(board)
  6. conflicts = 0
  7. # W
  8. for i in range(0,queen):
  9. if(board[i] == board[queen]):
  10. conflicts += 1
  11. break
  12. # E
  13. for i in range(queen+1, n):
  14. if(board[i] == board[queen]):
  15. conflicts += 1
  16. break
  17. # NW
  18. for i in range(0,queen):
  19. if(board[i] == board[queen] + queen - i):
  20. conflicts += 1
  21. break
  22. # SW
  23. for i in range(0,queen):
  24. if(board[i] == board[queen] - queen + i):
  25. conflicts += 1
  26. break
  27. # NE
  28. for i in range(queen+1, n):
  29. if(board[i] == board[queen] - queen + i):
  30. conflicts += 1
  31. break
  32. # SE
  33. for i in range(queen+1, n):
  34. if(board[i] == board[queen] + queen - i):
  35. conflicts += 1
  36. break
  37. return conflicts
  38. def checkBoard(board):
  39. for i in range(0, len(board)):
  40. if(findConflicts(board, i) > 0):
  41. return False
  42. return True
  43. def solveBoard(board):
  44. colNames = ['a','b','c','d','e','f','g','h']
  45. steps = 10000
  46. moves = 0
  47. lastMoved = None
  48. for i in range(0, steps):
  49. if(checkBoard(board) == True):
  50. print "moves: "+str(moves)
  51. return board
  52. randQueen = random.randint(0, len(board)-1)
  53. currentConflicts = findConflicts(board, randQueen)
  54. if(currentConflicts > 0 and randQueen != lastMoved):
  55. colConflicts = []
  56. for row in range(1, len(board)+1):
  57. testBoard = list(board)
  58. testBoard[randQueen] = row
  59. colConflicts.append(findConflicts(testBoard, randQueen))
  60. minConflict = min(colConflicts)
  61. minConflictRows = [t for t, u in enumerate(colConflicts) if u == minConflict]
  62. newRow = choice(minConflictRows)+1
  63. if(board[randQueen] != newRow):
  64. print colNames[randQueen]+str(board[randQueen])+" -> "+colNames[randQueen]+str(newRow)
  65. board[randQueen] = newRow
  66. lastMoved = randQueen
  67. moves += 1
  68. return None
  69. if(len(sys.argv) >= 2):
  70. board = [int(x) for x in sys.argv[1].split(",")]
  71. else:
  72. print "missing board argument"
  73. sys.exit(0)
  74. colNames = ['a','b','c','d','e','f','g','h']
  75. boardToSolve = list(board)
  76. for i in range(len(boardToSolve)):
  77. boardToSolve[i] = colNames[i]+str(boardToSolve[i])
  78. print ",".join([str(n) for n in boardToSolve])
  79. board = solveBoard(board)
  80. if(board is None):
  81. print "Solution not found"
  82. else:
  83. for i in range(len(board)):
  84. board[i] = colNames[i]+str(board[i])
  85. print ",".join([str(n) for n in board])

comments powered by Disqus