12 dominating knights puzzle (backtracking)

前端 未结 5 1985
感动是毒
感动是毒 2021-02-07 05:47

I\'ve been searching for hours and haven\'t found a fully working solution for this kind of puzzle yet. So I followed similar problem with bishops.

What I need to do is

5条回答
  •  广开言路
    2021-02-07 06:42

    Your attempt is very inefficient, so it might be just because of the inefficiency that you can't find a solution.

    First, it's pointless to try to place 12 knights. Place 6 knights onto white fields. Find all solutions. Then any solution with 6 knights on white fields can be mirrored and gives 6 knights on black fields, and you combine that.

    Second, you are trying to place the knights in any order. But the order is arbitrary. So place them in some sorted order, like a1, c1, e1, g1, b2, d2, f2, h2, a3... etc. That reduces the number of choices by a factor 6! or 720 (in your original case 12! = billions).

    To be efficient: Number the white fields from 0 to 31. Number the black fields from 0 to 31. For each black field, find the indices of the white fields that can be reached by a knight on that field, and create a 32 bit bitmap representing those fields.

    Then:

    for (int k1 = 0; k1 < 27; ++k1)
        for (int k2 = k1+1, k2 < 28; ++k2)
            for (int k3 = k2+1; k3 < 29; ++k3)
                for (int k4 = k3+1; k4 < 30; ++k4)
                    for (int k5 = k4+1; k5 < 31; ++k5)
                       for (int k6 = k5+1; k6 < 32; ++k6)
                           if ((bits [k1] | bits [k2] | bits [k3] | bits [k4] | bits [k5] | bits [k6]) == 0xffffffff)
                               // got a solution!!!
    

    That's less than a million checks, so it would take a few milliseconds.

    PS. Your combination of placeKnight / removeKnight doesn't work. For example, c3 is covered both by a knight on b1 or on a2. If you place a knight on a2, then on b1, then remove the knight on b1, you set c3 to "not covered".

    PS. If you had a bigger chessboard, you would take shortcuts to reduce the number of possibilities. For example, field a1 must be covered by a knight on the first row, second row, or b3 on the third row. So if you try to put a knight on a field c3 or later, and a1 isn't covered, there is no need to try putting a knight on that field or a later field at all.

提交回复
热议问题