Python 八皇后解法(非递归版本)

import Stack # 假设已经定义好栈类

def conflict(state, nextX):
    '''判断新皇后的落点是否与前一皇后冲突
        1、如果新皇后与前一皇后在同一列,则 state[i] == nextX
        2、如果新皇后与前一皇后在同一行,则 i == nextY
        3、如果新皇后在前一皇后右对角线 ,则 nextX - state[i] == nextY - i
        4、如果新皇后在前一皇后左对角线,则 state[i] - nextX == nextY - i
    '''
    nextY = len(state)
    for i in range(nextY):
        if abs(state[i] - nextX) in (0, nextY - i):
            return True
    return False

def queen(num = 8, state = ()):
    st = Stack.Stack()
    st.push([0,state]) # 每一个位置包含下一搜索位置及相应的位置状态信息

    while not st.is_empty():
        now_queen = st.pop() # 从栈中弹出一个位置
        
        for pos in range(now_queen[0], num):
            temp_state = now_queen[1]
            if not conflict(temp_state, pos):
                if len(temp_state) == num - 1:
                   temp_state = temp_state + (pos,)
                   print (temp_state)
                else:
                    now_queen[0] = pos + 1
                    st.push(now_queen)
                    next_queen = [0, temp_state + (pos,)]
                    st.push(next_queen)

 

 

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值