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 )
    
            
            

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

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

  • 相关阅读:
    PAT乙级1014.福尔摩斯的约会 (20)(20 分)
    PAT乙级1013.数素数
    PAT乙级1012.数字分类 (20)(20 分)
    PAT乙级1011.A+B和C (15)(15 分)
    PAT乙级1025.反转链表 (25)
    PAT乙级1020.月饼(20)
    PAT乙级1015.德才论(25)
    PAT乙级1010.一元多项式求导(25)
    PAT乙级1009.说反话(20)
    PAT乙级1008.数组元素循环右移问题(20)
  • 原文地址:https://www.cnblogs.com/mryrs/p/7630407.html
Copyright © 2011-2022 走看看