有没有更有效的方法来计算网格中所有可能路径的位移?

时间:2019-03-27 01:18:32

标签: python dynamic-programming

我正在尝试用Python编写一种算法,该算法可以计算并存储n x m网格中所有可能路径的最大位移。没有障碍。我们从原点开始,每次可以向上或向右移动网格一个单位长度。我为每个路径(使用预定义的公式)计算最大位移,然后将该位移附加到列表中,以便在程序完成后可以对其进行访问。

我可以毫无问题地计算出每个路径的最大位移,并且我已经实现了我的解决方案,使得仅保存了计算结果,因为没有这种情况,RAM就会过载。网格大小为10 x 10时,它似乎可以正常工作。但是,当我考虑使用较大的网格(例如30 x 30)时,由于要创建的路径数量众多,因此计算将花费大量时间。我正在使用的代码如下。

# This function creates the initial path list and calls the function
# to create all possible paths
def findPaths(startRow,startCol,endRow,endCol): 
    path = [0 for d in range(endRow+endCol-startRow-startCol-1)] 
    findPathsUtil(endRow,endCol,startRow,startCol,path,0)

# This function is called iteratively until either of the if conditions are met
def findPathsUtil(endRow,endCol,currRow,currCol,path,indx):
    global count_global

    # If we reach the bottom of maze, we can only move right
    if currRow==(endRow-1):
        # Completes the remainder of the path until it hits the end point
        for k in range(currCol,endCol):
            path[indx+k-currCol] = (currRow,k)
        # Calculates the maximum displacement for the current path
        D_curr = max([abs( elem[1]/endCol - elem[0]/endRow ) for elem in path])
        # Append this new displacement to a list of all other found displacements
        D_list.append(D_curr)
        return

    # If we reach to the right most corner, we can only move down
    if currCol == (endCol-1):
        # Completes the remainder of the path until it hits the end point
        for k in range(currRow,endRow):
            path[indx+k-currRow] = (k,currCol)
        # Calculates the maximum displacement for the current path
        D_curr = max([abs( elem[1]/endCol - elem[0]/endRow ) for elem in path])
        # Append this new displacement to a list of all other found displacements
        D_list.append(D_curr)
        return

    # This is activated any time we have not yet hit one of the walls
    else:
        # add Current coordinate to the path list
        path[indx]=(currRow,currCol)
        findPathsUtil(endRow, endCol, currRow+1, currCol, path, indx+1)
        findPathsUtil(endRow, endCol, currRow, currCol+1, path, indx+1)

if __name__ == '__main__':

    # Initialize cell array to consider
    startRow = 0
    startCol = 0
    endRow = 3
    endCol = 3

    global D_list
    D_list = []

    # First find all displacements for all possible paths are store in global variable D_list
    findPaths(startRow,startCol,endRow+1,endCol+1)

我了解到30 x 30的网格具有与之关联的大量可能的路径,但是考虑到所有事物,有些程序认为网格要大得多。有什么方法可以大大降低此计算的时间复杂度?任何想法或建议将不胜感激。

0 个答案:

没有答案