在8×8格的国际象棋上摆放8个皇后,使其不能互相攻击,即任意两个皇后都不能处于同一行、同一列或同一斜线上,用Python编写程序,问有多少种摆法?并列举出所有摆法。

可以扩展问题以使用NxN大小的板来解决难题。

代码

'''N Queens problem'''

from functools import reduce
from itertools import chain


# queenPuzzle :: Int -> Int -> [[Int]]
def queenPuzzle(nCols):
    '''All board patterns of this dimension
       in which no two Queens share a row,
       column, or diagonal.
    '''

    def go(nRows):
        lessRows = nRows - 1
        return reduce(
            lambda a, xys: a + reduce(
                lambda b, iCol: b + [xys + [iCol]] if (
                    safe(lessRows, iCol, xys)
                ) else b,
                enumFromTo(1)(nCols),
                []
            ),
            go(lessRows),
            []
        ) if 0 < nRows else [[]]

    return go


# safe :: Int -> Int -> [Int] -> Bool
def safe(iRow, iCol, pattern):
    '''True if no two queens in the pattern
       share a row, column or diagonal.
    '''

    def p(sc, sr):
        return (iCol == sc) or (
                sc + sr == (iCol + iRow)
        ) or (sc - sr == (iCol - iRow))

    return not any(map(p, pattern, range(0, iRow)))


# ------------------------- TEST -------------------------
# main :: IO ()
def main():
    '''Number of solutions for boards of various sizes'''

    n = 8
    xs = queenPuzzle(n)(n)

    print(
        str(len(xs)) + ' solutions for a {n} * {n} board:\n'.format(n=n)
    )
    print(showBoards(10)(xs))

    print(
        fTable(
            '\n\n' + main.__doc__ + ':\n'
        )(str)(lambda n: str(n).rjust(3, ' '))(
            lambda n: len(queenPuzzle(n)(n))
        )(enumFromTo(1)(10))
    )


# ---------------------- FORMATTING ----------------------

# showBoards :: Int -> [[Int]] -> String
def showBoards(nCols):
    '''String representation, with N columns
       of a set of board patterns.
    '''

    def showBlock(b):
        return '\n'.join(map(intercalate('  '), zip(*b)))

    def go(bs):
        return '\n\n'.join(map(
            showBlock,
            chunksOf(nCols)([
                showBoard(b) for b in bs
            ])
        ))

    return go


# showBoard :: [Int] -> String
def showBoard(xs):
    '''String representation of a Queens board.'''
    lng = len(xs)

    def showLine(n):
        return ('.' * (n - 1)) + '♛' + ('.' * (lng - n))

    return map(showLine, xs)


# fTable :: String -> (a -> String) ->
#                     (b -> String) -> (a -> b) -> [a] -> String
def fTable(s):
    '''Heading -> x display function -> fx display function ->
                     f -> xs -> tabular string.
    '''

    def go(xShow, fxShow, f, xs):
        ys = [xShow(x) for x in xs]
        w = max(map(len, ys))
        return s + '\n' + '\n'.join(map(
            lambda x, y: y.rjust(w, ' ') + ' -> ' + fxShow(f(x)),
            xs, ys
        ))

    return lambda xShow: lambda fxShow: lambda f: lambda xs: go(
        xShow, fxShow, f, xs
    )


# ----------------------- GENERIC ------------------------

# enumFromTo :: (Int, Int) -> [Int]
def enumFromTo(m):
    '''Integer enumeration from m to n.'''
    return lambda n: range(m, 1 + n)


# chunksOf :: Int -> [a] -> [[a]]
def chunksOf(n):
    '''A series of lists of length n, subdividing the
       contents of xs. Where the length of xs is not evenly
       divible, the final list will be shorter than n.
    '''
    return lambda xs: reduce(
        lambda a, i: a + [xs[i:n + i]],
        range(0, len(xs), n), []
    ) if 0 < n else []


# intercalate :: [a] -> [[a]] -> [a]
# intercalate :: String -> [String] -> String
def intercalate(x):
    '''The concatenation of xs
       interspersed with copies of x.
    '''
    return lambda xs: x.join(xs) if isinstance(x, str) else list(
        chain.from_iterable(
            reduce(lambda a, v: a + [x, v], xs[1:], [xs[0]])
        )
    ) if xs else []


# MAIN ---
if __name__ == '__main__':
    main()

输出结果

92 solutions for a 8 * 8 board:............................  .......  .......  .......  .......  .......  .......
.......  .......  .......  .......  .......  .......  .......  .......  .......  .......
.....................  .......  .......  .......  ..............  ..............
.......  .......  .......  ..............♛  ♛.......  .......  .......  .......  .......
.......  .......  ..............  .......  ..............  ..............  ..............  .......  .......  ..............  ............................  .......
.......  .......  .......  .......  .......  .......  .......  .......  ..............
.......  .......  .......  .......  .......  .......  .......  .......  .......  .......

.......  .......  .......  .......  .......  .......  .......  .......  .......  .......
.......  .......♛  ♛.......  .......  .......  .......  .......  .......  .......  .......
.......  .......  .......  .......  .......  .......  ..............  .......  .......
.......♛  ♛.......  .......  ..............♛  ♛.......  .......  .......  .......  ..............  .......  .......♛  ♛.......  .......  ..............  .......♛  ♛.......  .......
.......  .......  .......  .......  .......  .......  ..............  ..............
.......  .......  .......  .......  .......  ..............  .......  .....................  .......  .......  ..............  .......  .......  .......  .......  .......

.......  .......  .......  .......  .......  .......  .......  .......  .......  .......
.......  .......  .......  .......  .......  .......  .......  .......♛  ♛..............
.......  .......  ............................  .......  .......  .......  ..............  .....................  .......  .....................  ...................................  .......  .......  .......  ..............  .......  .......
.......  .......  .......  .....................  .......  .......  .......  .......
.......  .......  .......  .......  .......  ..............  .......  .......  .......
..............  .......  .......  .......  .......  .......  .......  .......  .......

.......  .......  .......  .......  .......  .......  .......  .......  .......  .......
.......  .......  .......  .......  .......  .......  .......  .......  .......  .......
.......  .......  .......  .......  ..............♛  ♛.......  ..............♛  ♛.......
..............  .......  .......  .......  .......  .......  .......  .......  ..............  .......  ..............  ..............  .......  ..............  ..............  .....................♛  ♛.......  .......  .......♛  ♛.......  .......  .......
..............  .......  .......  .......  .......  .......  .......  .......  .......
.......  ..............  .......  .......  .......  .......  .......  .......  .......

.......  .......  .......  .......  .......  .......  .......  .......  .......  .......
.......  .......  .......  .....................♛  ♛.....................  .......
.......  .......  .....................  .......  .......  .....................
..............  .......  .......  .......  .......  .......  .......  .......  .......
.......  ..............  .......  ..............  ..............  .......  .....................  .......  .......  .......  .......  .......  .......  .......  ..............  .......  ..............  .......  .......  .......  .......  ..............
.......  ..............  .......  .......  .......  .......  .......  .......  .......

.......  .......  .......  .......  .......  .......  .......  .......  .......  .......
.......  .......  .......  .......  .......  .......  .......  .......  .......  .......
.......  .......  .......♛  ♛..............  .......♛  ♛..............  .......  .......
.....................  .......  .......  .......  .......  .......  .......  .......
.......  .......  .......  ..............  .......  ..............  ..............
..............  .......  .......  .......♛  ♛.......  .......  .......♛  ♛..............
.......  ..............  .......  .......  .......  .......  .......  .......  ..............  .......  .......  .......  .......  .......  .......  .......  .......  ..............  .......  .......  .......  .......  .......  .......  .......  .......  .......
.......  .......  ..............♛  ♛.......  .......  .......  .......  .......  .......
.......  .......  .......  .......  .......  .......  ............................
............................  .....................  .......  .....................  .......  .......  .......  ..............  .......  .......  .......  ..............  ..............  .......  .......  .......  .....................  .......
..............  .......  .......  .......  ..............  .......  .......  .......
.......  .......  .......  .......  .......  .......  .......  .......  .......  .......

.......  .......  .......  .......  .......  .......  .......  .......  .......  .......
.......  .......  .......  .......  .......  .......  .......  .......  .......  ..............  .......  .......  .......  ..............  .......  .......  .......  .......
.......  ..............  .......  .......  .......  .......♛  ♛..............  .....................  .......  .......♛  ♛.......  ..............  .......  .......♛  ♛.......
.......  .......  ..............  ..............  .......  .......  .......  .......
.......  .....................  .......  ..............  .......  .......  .......
..............  .......  .......  .......  .......  .......  ..............  .......

.......  .......  .......  .......  .......  .......  .......  .......  ..............♛
♛.......  .......  .......  .......  .......  .......  .......  .......  .......  .......
.......  .......  ..............  ..............  .......  .......  .......  .......
.......♛  ♛.......  .......  .......  .......  .......  .......♛  ♛..............  .......
.......  .......♛  ♛.......  ..............  ..............  .......  ..............
.......  .......  .......  ............................  ..............  .......
.......  .......  ..............  .......  .......  .......  .......  .......  .......
.......  .......  .......  .......  .......  .......  .......  .......  .......  .......

.....................  .....................
.......  .......
.......  .......
.......  .......
.......  .......
.......  .......


Number of solutions for boards of various sizes:

 1 ->   1
 2 ->   0
 3 ->   0
 4 ->   2
 5 ->  10
 6 ->   4
 7 ->  40
 8 ->  92
 9 -> 352
10 -> 724
  • 4
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

开了又败的花墙

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值