一个方格表的问题

 

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

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 )

        
        

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

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

posted on 2017-10-06 02:17  yrsss  阅读(167)  评论(0编辑  收藏  举报