Skip to content

Instantly share code, notes, and snippets.

@alex-berezan
Created May 26, 2018 04:28
Show Gist options
  • Save alex-berezan/ce81201f840afa3b1d70861d2a2ad075 to your computer and use it in GitHub Desktop.
Save alex-berezan/ce81201f840afa3b1d70861d2a2ad075 to your computer and use it in GitHub Desktop.
def attacks_any_queen(q, queens, count):
(i, j) = q
for k in range(0, count):
(qi, qj) = queens[k]
if i == qi or j == qj or (abs(i-qi) == abs(j-qj)):
return True
return False
def place_queen(queens, q_index=0):
n = 8
for i in range(0, n):
for j in range(0, n):
if attacks_any_queen((i, j), queens, q_index):
continue
queens[q_index] = (i, j)
if q_index == len(queens)-1:
return True
placed_next = place_queen(queens, q_index+1)
if placed_next:
return True
queens[q_index] = None
return False
queens = [None]*8
placed = place_queen(queens)
print("placed={}, queens: {}".format(placed, queens))
# [(0, 0), (1, 4), (2, 7), (3, 5), (4, 2), (5, 6), (6, 1), (7, 3)]
# Q _ _ _ _ _ _ _
# _ _ _ _ Q _ _ _
# _ _ _ _ _ _ _ Q
# _ _ _ _ _ Q _ _
# _ _ Q _ _ _ _ _
# _ _ _ _ _ _ Q _
# _ Q _ _ _ _ _ _
# _ _ _ Q _ _ _ _
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment