Created
July 28, 2022 19:08
-
-
Save kosugi/176598202d10c3aadebf02091ae7f0ad to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -*- coding: utf-8 -*- | |
import itertools | |
def is_conflicted(qs, x ,y): | |
for (v, w) in qs: | |
if v == x or w == y or abs(v - x) == abs (w - y): | |
return True | |
def solve(N, n, qs): | |
if n == 0: | |
return qs | |
for pos in itertools.product(range(N - n, N), range(N)): | |
if pos not in qs and not is_conflicted(qs, *pos): | |
r = solve(N, n - 1, (*qs, pos)) | |
if r: | |
return r | |
if __name__ == '__main__': | |
import argparse | |
parser = argparse.ArgumentParser(description='solve N queens puzzle') | |
parser.add_argument('N', metavar='N', type=int, nargs='?', default=8, help='num queens') | |
args = parser.parse_args() | |
print(solve(args.N, args.N, ())) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment