python通用编程二阶段:八皇后

本文详细介绍了使用递归算法解决经典的八皇后问题,探讨了如何在8×8的棋盘上放置八个皇后,确保任意两个皇后不在同一行、列或斜线上。通过Python代码实现了问题的求解,并展示了所有可能的解决方案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

八皇后问题:
在8×8格的国际象棋上摆放八个皇后,使其不能互相攻击,即任意两个皇后都不能处于同一行、同一列或同一斜线上,问有多少种摆法

def conflict(chesses_placed, next_chess_xcor):
     """
    This is a conflicting function defined
    :param chesses_placed: use a tuple to save chesses placed
    :param next_chess_xcor: the x coordinate of next chess to place
    :return: true or false
    """
    # get the next y coordinate by chessed placed
    next_chess_ycor = len(chesses_placed)

    # use next chess y coordinate to confirm the count of loop
    for i in range(next_chess_ycor):

        # use absolute value to confirm the same oblique line
        if abs(chesses_placed[i] - next_chess_xcor) in (0, abs(i - next_chess_ycor)):
            return True
    return False


def place_queens(num=8, chesses_placed_tuple=()):
    """
    This is a placing queens function defined
    :param num: the count of queens
    :param chesses_placed_tuple: such as (1, 5, 0)
    :return: a generator
    """
    for i in range(num):
        if not conflict(chesses_placed_tuple, i):

            # judge the last line
            if len(chesses_placed_tuple) == num - 1:
                yield (i,)
            else:

                # get one bye one element from the generator
                for j in place_queens(num, chesses_placed_tuple + (i,)):
                    # superimpose elements to the newest tuple
                    yield (i,) + j


res = list(place_queens(8))
print(res)
print(len(res))

简版:

def queen(A, cur=0):
    if cur == len(A):
        print(A)
        return 0
    for col in range(len(A)):
        A[cur], flag = col, True
        for row in range(cur):
            if A[row] == col or abs(col - A[row]) == cur - row:
                flag = False
                break
        if flag:
            queen(A, cur+1)
queen([None]*8)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值