Skip to content

Instantly share code, notes, and snippets.

@yangyushi
Created October 21, 2019 11:49
Show Gist options
  • Save yangyushi/f6589d150b9fef4362d5de387d11c506 to your computer and use it in GitHub Desktop.
Save yangyushi/f6589d150b9fef4362d5de387d11c506 to your computer and use it in GitHub Desktop.
get all possible configurations in n queens problem
def conflict(conf):
for i in range(len(conf) - 1):
if conf[i] == conf[-1]:
return True
if len(conf) - i - 1 == conf[-1] - conf[i]:
return True
elif len(conf) - i - 1 == conf[i] - conf[-1]:
return True
return False
def n_queen(size, solutions, level=0, config=None):
if level == size: solutions.append(config)
else:
if level == 0:
config = [None]
for i in range(size):
config[level] = i
n_queen(size, solutions, level+1, config.copy())
else:
config.append(None)
for i in range(size - 1):
next_pos = (config[level - 1] + i + 1) % size
config[level] = next_pos
if not conflict(config):
n_queen(size, solutions, level+1, config.copy())
if __name__ == "__main__":
solutions = []
n_queen(8, solutions)
print(len(solutions))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment