python-八皇后问题


#矩阵表示棋盘

#字典queenList表示已放置成功的皇后,key值代表列,value代表行


#encoding:utf-8
import numpy as np


#判断该位置是否为危险位置
def IsSafe(col,row,queenList): 
    for tempCol in range(col):
        tempRow=queenList[tempCol]
        if tempCol==col: #列重复
            return False
        if tempRow==row: #行重复
            return False
        if col-row==tempCol-tempRow or col+row==tempCol+tempRow: #正负对角线重复
            return False
    return True

#递归放置皇后位置
def PutQueen(col,queenList):
     row=0
     foundSafePos=False
     if col==8:  #递归中止条件(成功)
         foundSafePos=True
     else:
         while row<8 and not foundSafePos:
             if IsSafe(col,row,queenList):
                 queenList[col]=row
                 foundSafePos=PutQueen(col+1,queenList)
                 if not foundSafePos:
                     row=row+1
             else:
                 row=row+1
     return foundSafePos

#矩阵的形式打印八皇后(1为皇后)
def showQueen(matrix,queenList):
    for col in queenList.keys():
        row=queenList[col]
        matrix[row][col]=1
    print matrix


def main():
    matrix=np.zeros([8,8],np.int) #棋盘矩阵
    queenList={} #key==col,value==row
    cols=matrix.shape[1] #获取矩阵的列数
    flag=PutQueen(0,queenList)
    if flag==True:
        showQueen(matrix,queenList)
    else:
        print '失败'




if __name__=="__main__":
    main()

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值