Skip to content

Instantly share code, notes, and snippets.

@mauricioaniche
Last active September 30, 2019 15:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mauricioaniche/e66d77e55605486dbf114efcfc3aff37 to your computer and use it in GitHub Desktop.
Save mauricioaniche/e66d77e55605486dbf114efcfc3aff37 to your computer and use it in GitHub Desktop.
Brute force implementation of the eight queens problem
def bf_queen(m):
return bf_queen_rec(m, 0)
def check(r, v):
pos_1, pos_2 = v, v
for j in r:
pos_1 = pos_1 - 1
if m[j] == pos_1:
return False
pos_2 = pos_2 + 1
if m[j] == pos_2:
return False
return True
def win(m):
if len(set(m)) < 8:
return False
for i in range(0, 8):
before = range(i - 1, 0, -1)
after = range(i + 1, 8)
if not check(before, m[i]) or not check(after, m[i]):
return False
return True
def bf_queen_rec(m, col):
if col > 7:
return
for i in range(0, 7):
bf_queen_rec(m, col + 1)
if win(m):
return m
else:
m[col] = m[col] + 1
m[col] = 1
# m = [1] * 8
m = [5, 1, 8, 4, 2, 6, 2, 6] # the solution is 5, 1, 8, 4, 2, 7!!!, 3!!!, 6
solution = bf_queen(m)
print(solution)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment