Solving N-Queens Problem… How far can we go?

后端 未结 9 931
闹比i
闹比i 2020-12-09 03:23

The N-Queens Problem:

This problem states that given a chess board of size N by N, find the different permutations in which N queens can be placed on the board with

相关标签:
9条回答
  • 2020-12-09 03:59

    As to what is the largest N solved by computers there are references in literature in which a solution for N around 3*10^6 has been found using a conflict repair algorithm (i.e. local search). See for example the classical paper of [Sosic and Gu].

    As to exact solving with backtracking,there exist some clever branching heuristics which achieve correct configurations with almost no backtracking. These heuristics can also be used to find the first-k solutions to the problem: after finding an initial correct configuration the search backtracks to find other valid configurations in the vicinity.

    References for these almost perfect heuristics are [Kale 90] and [San Segundo 2011]

    0 讨论(0)
  • 2020-12-09 04:03

    Which Prolog system are you using? For example, with recent versions of SWI-Prolog, you can readily find solutions for N=80 and N=100 within fractions of a second, using your original code. Many other Prolog systems will be much faster than that.

    The N-queens problem is even featured in one of the online examples of SWI-Prolog, available as CLP(FD) queens in SWISH.

    Example with 100 queens:

    ?- time((n_queens(100, Qs), labeling([ff], Qs))).
    Qs = [1, 3, 5, 57, 59 | ...] .
    2,984,158 inferences, 0.299 CPU in 0.299 seconds (100% CPU, 9964202 Lips)
    

    SWISH also shows you nices image of solutions.

    Here is an animated GIF showing the complete solution process for N=40 queens with SWI-Prolog:

    0 讨论(0)
  • 2020-12-09 04:10

    a short solution presented by raymond hettinger at pycon: easy ai in python

    #!/usr/bin/env python
    from itertools import permutations
    n = 12
    cols = range(n)
    for vec in permutations(cols):
        if (n == len(set(vec[i] + i for i in cols))
              == len(set(vec[i] - i for i in cols))):
            print vec
    

    computing all permutations is not scalable, though (O(n!))

    0 讨论(0)
提交回复
热议问题