码迷,mamicode.com
首页 > 其他好文 > 详细

一个方格表的问题

时间:2017-10-06 10:39:31      阅读:98      评论:0      收藏:0      [点我收藏+]

标签:print   无法   影响   val   路径   com   temp   [1]   运行   

技术分享

 

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

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 )

        
        

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

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

一个方格表的问题

标签:print   无法   影响   val   路径   com   temp   [1]   运行   

原文地址:http://www.cnblogs.com/mryrs/p/7630407.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!