Python 实现八皇后问题

初学 Python , 写了一个八皇后的小程序,虽然算法效率不高,但这次是第一个用python实现

 

chess=[[0 for col in range(8)] for row in range(8)]
pos =0
i=0
flag =0
    
def check(i,pos):  
    if i==0:
        return True
    
    for counter in range(i):
        if chess[counter][pos]==1:
            return False
        
    for x in range(min(i,pos)):
        if chess[i-x-1][pos-x-1]==1:
            return False
    
    if pos<7:
        for y in range(min(i,7-pos)):
            if  chess[i-y-1][pos+y+1]==1:
                return False
    
    return True
        
while i<8:
    chess[i][pos]=1
    
    if check(i,pos):
        i=i+1
        pos=0
    else:
        chess[i][pos]=0
        while pos<7 and not check(i,pos):
            pos=pos+1
        
        if pos<=7 and check(i,pos): 
            chess[i][pos]=1
            i=i+1
            pos=0
        else:
            if (chess[i-1].index(1))<7:
                pos = chess[i-1].index(1)+1
                chess[i-1][pos-1]=0
                i=i-1
            else:
                if i>=2:
                    pos =chess[i-2].index(1)+1
                    chess[i-1][7]=0
                    chess[i-2][pos-1]=0
                    i=i-2
                else:
                    break
                

    if 1 in chess[7]:
        flag=flag+1
##        print "%d:Found:"%(flag)
##        
##        for k in range(len(chess)):
##            print chess[k]
##        
##        print
##        print "*"*30
       
        if (chess[7].index(1))<7:
            pos = chess[7].index(1)+1
            chess[7][pos-1]=0
            i=7
        else:
            pos =chess[6].index(1)+1
            chess[7][7]=0
            chess[6][pos-1]=0
            i=6
print "there are %d solutions" %flag

                
                    
                
                
        

 

去掉程序中的注释,可以得到全部解:

 

******************************
90:Found:
[0, 0, 0, 0, 0, 0, 0, 1]
[0, 1, 0, 0, 0, 0, 0, 0]
[0, 0, 0, 0, 1, 0, 0, 0]
[0, 0, 1, 0, 0, 0, 0, 0]
[1, 0, 0, 0, 0, 0, 0, 0]
[0, 0, 0, 0, 0, 0, 1, 0]
[0, 0, 0, 1, 0, 0, 0, 0]
[0, 0, 0, 0, 0, 1, 0, 0]

******************************
91:Found:
[0, 0, 0, 0, 0, 0, 0, 1]
[0, 0, 1, 0, 0, 0, 0, 0]
[1, 0, 0, 0, 0, 0, 0, 0]
[0, 0, 0, 0, 0, 1, 0, 0]
[0, 1, 0, 0, 0, 0, 0, 0]
[0, 0, 0, 0, 1, 0, 0, 0]
[0, 0, 0, 0, 0, 0, 1, 0]
[0, 0, 0, 1, 0, 0, 0, 0]

******************************
92:Found:
[0, 0, 0, 0, 0, 0, 0, 1]
[0, 0, 0, 1, 0, 0, 0, 0]
[1, 0, 0, 0, 0, 0, 0, 0]
[0, 0, 1, 0, 0, 0, 0, 0]
[0, 0, 0, 0, 0, 1, 0, 0]
[0, 1, 0, 0, 0, 0, 0, 0]
[0, 0, 0, 0, 0, 0, 1, 0]
[0, 0, 0, 0, 1, 0, 0, 0]

******************************
there are 92 solutions

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值