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));
}
}