计算迷宫中唯一路径的数量

时间:2014-11-04 03:00:34

标签: algorithm graph dynamic-programming backtracking

我知道在矩阵中计算路径[0,0]到[n,n]的回溯方法。但无法通过动态编程解决它。如果没有回溯,它甚至可能吗?

您只能移动rightdown

1 1 1 1
1 0 1 1
1 1 0 1
1 1 1 1
`

从左上角到右下角的路径数是4

3 个答案:

答案 0 :(得分:3)

是的。假设p(i,j)是到i,j的部分路径的数量。如果我们使用零索引,那么你想要的是p(n-1,n-1)。你知道的是p(0,0)= 1,如果你可以从p(i-1,j)到p(i,j),那么p(i,j)是左边值的总和,如果你可以从p(i,j-1)到p(i,j)旅行,那么上面的值。

所以你用这一切填写矩阵。差不多就是DP是什么:矩阵填充。一旦你弄清楚如何填写你已经完成的矩阵。

答案 1 :(得分:0)

    static int numPath = 0;
    // Take one sol[][] of same size as original matrix just to see your paths.
    private static boolean MazeSolvingAllPaths(int [][] matrix, int x, int y, int[][] sol) {


        //Base case
        if(x == (sizeofMatrix -1) && y == (sizeofMatrix -1)) {
            sol[x][y] = 1;
            numPath++; // Path found so increase numPath here
            return true;
        }
        if(isSafeAllPaths(matrix, x, y) == true && matrix[x][y] == 1) {
            sol[x][y] = 1; // Mark this as solution path in solution matrix
            // Go right and down for (x, y)
            boolean var1 = MazeSolvingAllPaths(matrix, x, y+1, sol);
            boolean var2 = MazeSolvingAllPaths(matrix, x+1, y, sol);
            // If atleast one solution i found then return true
            if(var1 || var2) {                  
                return true;
            } else { // means both var1 and var2 are false
                sol[x][y] = 0;// unmark because i couldn't find path
                return false;
            }
        }
        return false;
    }

答案 2 :(得分:0)

是的,您可以使用动态编程来解决此问题。

  • 给定M x N迷宫,初始化具有相同尺寸的数组paths。设paths[i][j]为可能路径的数量 maze[0][0]maze[i][j]
  • paths[0][0]初始化为1
  • 如果maze[i][j] == 0,则paths[i][j] = 0其他paths[i][j] = paths[i-1][j] + paths[i][j-1]

这是一个Python实现:

def number_of_paths(maze):
    paths = [[0 for col in range(len(maze[0]))] for row in range(len(maze))]
    paths[0][0] = 1

    for row in range(len(maze)):
        for col in range(len(maze[0])):
            if maze[row][col] == 0:
                paths[row][col] = 0
            else:
                if row != 0:
                    paths[row][col] += paths[row-1][col]
                if col != 0:
                    paths[row][col] += paths[row][col-1]
    return paths[-1][-1]

maze = [[1, 1, 1, 1],
        [1, 0, 1, 1],
        [1, 1, 0, 1],
        [1, 1, 1, 1]]

print(number_of_paths(maze))  # 4