免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 1093 | 回复: 0
打印 上一主题 下一主题

我给出的第一个八皇后的解 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2009-06-25 23:15 |只看该作者 |倒序浏览

                                                                  用蛮力法解决,耗了三分钟,一共得到了92个解,不知道有谁有解的个数的确切数字。最近迷python,就用它来实现了,水平有限,请各位高手指点。拿了个人家实现,几乎在1s内就实现了,哎,惭愧阿,我要摆脱蛮力法。
   PS:今天利用闲暇时间想了想,要提高效率,最终就是要给出0-7八个数字的全排列,这样测试空间就会小很多。不过我还没有想出如何给出一个比较高效的全排列。
import time
def display (x):
    i = 0
    while i8:
        print x
        i+=1
def display_method (method):
    x = [[0 for i in range(8)] for j in range(8)]
    for i in range(8):
        x[method[0]][method[1]]=1
    display(x)
def stupid_method():
    index=1
    for pos1 in range(8):
        for pos2 in range(8):
            for pos3 in range(8):
                for pos4 in range(8):
                    for pos5 in range(8):
                        for pos6 in range(8):
                            for pos7 in range(8):
                                for pos8 in range(8):
                                    if True ==test(pos1 ,pos2 ,pos3,pos4,pos5,pos6,pos7,pos8):
                                        print "This is "+str(index) + " method"
                                        index+=1
def test(pos1 ,pos2 ,pos3,pos4,pos5,pos6,pos7,pos8) :
    method =([0,pos1],[1,pos2],[2,pos3],[3,pos4],[4,pos5],[5,pos6],[6,pos7],[7,pos8])
    for i in range(8):
        for j in range(i+1,8):
            if attack(method,method[j])==True:
                return False
    print "**************************"
    display_method(method)
    return True
def attack(x,y):
    if x[1] == y[1]:
        return True
    if ((x[0]-y[0])**2) == ((x[1]-y[1])**2):
        return True
    return False
x = [[0 for i in range(8)] for j in range(8)]
cur_time1=time.time()
print "Start time "+time.strftime( "%Y-%m-%d %X", time.localtime() )
stupid_method()
cur_time2=time.time()
print "End time "+time.strftime( "%Y-%m-%d %X", time.localtime() )
print "Waste time "+str(cur_time2-cur_time1)+" seconds"
               
               
               
               
               
               
               
               
               
               

本文来自ChinaUnix博客,如果查看原文请点:http://blog.chinaunix.net/u2/72023/showart_1977608.html
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP