zoukankan      html  css  js  c++  java
  • 一个方格表的问题

    一开始我想到的解法如下:

    num=0
    start=[0,0]
    all_x=12
    all_y=12
    def go(st):
        global num
        if st[0]==all_x and st[1]==all_y:
            num+=1
        else:
            if st[0]==all_x:
                new=[st[0],st[1]+1]
                go(new)
            elif st[1]==all_y:
                new=[st[0]+1,st[1]]
                go(new)
            else:
                new=[st[0]+1,st[1]]
                go(new)
                new=[st[0],st[1]+1]
                go(new)
    go(start)
    print(num)

    代码很短也很容易理解,一开始测试的是2X2的 程序运行很快,但是测试15X15的时候程序就很慢很慢了 20X20几乎是程序无法运行结束,仔细想了想发现:程序进行了大量重复的递归(相同的坐标进行重复的求解) 于是有了下面的改进:

    while True:
        all_x=eval(input('请输入方格宽度'))
        all_y=all_x
        num=0
        start=[0,0]
        tempk=[]
        tempv=[None]*(all_x+1)*(all_y+1)
        def record_in(new):
            tempk.append(new)
            tempv[tempk.index(new)]=go(new)
        def get_record(new):
            return tempv[tempk.index(new)]
        def go(st):
            if st[0]==all_x and st[1]==all_y:
                return 1
            else:
                if st[0]==all_x:
                    new=[st[0],st[1]+1]
                    if new not in tempk:
                        record_in(new)
                    return get_record(new)
                elif st[1]==all_y:
                    new=[st[0]+1,st[1]]
                    if new not in tempk:
                        record_in(new)
                    return get_record(new)
                else:
                    new1=[st[0]+1,st[1]]
                    new2=[st[0],st[1]+1]
                    if new2  not in tempk and new1 not in tempk:
                        record_in(new1)
                        record_in(new2)
                    elif new1 in tempk:
                        record_in(new2)
                    elif new2 in tempk:
                        record_in(new1)
                    return get_record(new1)+get_record(new2)
    
        num=go(start)
        print(num )
    
            
            

    用了列表来当做一个容器,来存储从起始坐标到终点间经过的每个坐标到达终点的路径数,这样当遇到重复的坐标时无需再进行递归只需从列表中取值即可。

    可见算法对程序的效率影响之大。

  • 相关阅读:
    ios-表视图-demo4-内容自己适应高度
    ios-表视图-demo3-单选
    应用管理的实现
    初识MVC和KVC
    Xcode的常用快捷键
    UI基础--手写代码实现汤姆猫动画
    UI基础--UIView常见属性之frame、center、bounds、transframe属性
    UI基础--UIButton、懒加载
    ios多线程
    ios多线程简介
  • 原文地址:https://www.cnblogs.com/mryrs/p/7630407.html
Copyright © 2011-2022 走看看