grid move algorithm implementation in dynamic programming

拟墨画扇 提交于 2019-12-08 09:50:41

问题


Working on below problem,

Problem,

Given a m * n grids, and one is allowed to move up or right, find the different paths between two grid points.

I write two different versions of code, both are using dynamic programming (I tested it seems both of them return the same result)?

  • One version of algorithm has the assumption that if move r steps right, u steps up, we can find (1) solutions for r-1 steps right and u steps up, then combine with one final right step (2), solutions for r steps right and u-1 steps up, then combine with one final up step.

  • One version of algorithm has the assumption that if move r steps right, u steps up, we can (1) move right first for one step, then combine with solutions for r-1 steps right and u steps up, (2) move up first for one step, then combine with solutions for r steps right and u-1 steps up.

Source code in Python 2.7,

from collections import defaultdict
def move_right_up(rights, ups):
    path = defaultdict(list)
    for i in range(1, rights + 1):
        path[(i, 0)].append('r' * i)
    for j in range(1, ups + 1):
        path[(0, j)].append('u' * j)
    for i in range(1, rights+1):
        for j in range(1, ups+1):
            for k in path[(i-1, j)]:
                path[(i,j)].append(k+'r')
            for k in path[(i, j-1)]:
                path[(i,j)].append(k+'u')
    return path[(rights, ups)]

def move_right_up_v2(rights, ups):
    path = defaultdict(list)
    for i in range(1, rights + 1):
        path[(i, 0)].append('r' * i)
    for j in range(1, ups + 1):
        path[(0, j)].append('u' * j)
    for i in range(1, rights+1):
        for j in range(1, ups+1):
            for k in path[(i-1, j)]:
                path[(i,j)].append('r'+k)
            for k in path[(i, j-1)]:
                path[(i,j)].append('u'+k)
    return path[(rights, ups)]

if __name__ == "__main__":
    print sorted(move_right_up(2,3))
    print '============'
    print sorted(move_right_up_v2(2,3))

来源:https://stackoverflow.com/questions/41689176/grid-move-algorithm-implementation-in-dynamic-programming

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!