如果存在解,则迷宫问题的复杂性(应用回溯算法)

时间:2018-12-15 08:07:59

标签: recursion time-complexity recursive-backtracking

这是解决方案:使用递归树方法,看起来应该是指数的,即4次幂n。但是解决方法还不清楚。就像在采访中的描述一样。任何帮助表示赞赏。

class Solution {
    public static boolean hasPath(int[][] maze, int[] start, int[] destination) {
        boolean result = false;
        result = moveNext(maze, start[0], start[1], destination);
        return result;
    }
    public static boolean moveNext(int[][] graph, int i, int j, int[] destination) {
        if (i < 0 || i == graph.length ||
                j < 0 || j == graph[0].length ||
                graph[i][j] == 1)
           return false;
        graph[i][j] = 1;
        if (i == destination[0] && j == destination[1])
           return true;

        return moveNext(graph, i, j + 1, destination)
               || moveNext(graph, i + 1, j, destination)
               || moveNext(graph, i, j - 1, destination) 
               || moveNext(graph, i - 1, j, destination);
    }

    public static void main(String args[]) {
        int[][] maze = {
            { 0, 1, 1, 1 },
            { 1, 0, 1, 0 },
            { 1, 0, 1, 1 },
            { 0, 0, 0, 0 }
        };
        int start[] = { 0, 0 };
        int destination[] = { 3, 3 };
        System.out.println(hasPath(maze, start, destination));
    }
}

0 个答案:

没有答案