0

Here is the solution: Using recursion tree method, looks like it should be exponential i.e 4 power n. But solving it is not clear. Like how one would describe in an interview. Any help is appreciated.

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));
    }
}
yeputons
  • 8,478
  • 34
  • 67
  • It's not exponential, it does not terminate on some cases. Try empty 3x3 or 4x4 maze with `start = { 2, 2 }`, and `end = { 0, 0 }`. The solution may revisit the same cell multiple times and loop. – yeputons Dec 15 '18 at 08:10
  • it would terminate as soon as the destination coordinate matches with the current node co-ordinate. every node is set to 1 once visited to avoid the loop. Also, my question was more in general, not case specific. – Ronak Gupta Dec 15 '18 at 10:16
  • I believe it would never reach the destination coordinate on my example, it will just go between `(2, 2)` and `(2, 1)` in a loop. Asking about computation complexity of a non-terminating algorithm is pointless. – yeputons Dec 15 '18 at 10:18
  • 1
    I think you're missing something. I tested your specific case. it works! coz when it goes back to 2,2 it would see it is already set to 1 so return false and then execute the other moveNext call. – Ronak Gupta Dec 15 '18 at 10:27
  • I see, makes sense, missed that line. Then time complexity is proportional to the area of the maze. – yeputons Dec 15 '18 at 10:47
  • It's basically [depth-first search](https://en.wikipedia.org/wiki/Depth-first_search). – yeputons Dec 15 '18 at 10:49
  • Yeah that make sense. DFS is backtracking essentially. But to explain and verify how should i make the recurrence relation for it to prove its complexity is O(m*n) – Ronak Gupta Dec 15 '18 at 11:30
  • Also, what would be the space complexity for this and why? – Ronak Gupta Dec 16 '18 at 02:25

0 Answers0