I solved the maze backtracking question using a stack however could not find any other solution like that anywhere (to validate my solution is actually a valid one).
The problem statement is as follows -
Imagine a robot sitting on the upper left corner of grid with r rows and c columns. The robot can only move right or down but certain cells are "off limit" such that the robot cannot step on them. design an algorithm to find a path for the robot from the top left to the bottom right
My Solution (java) is as follows -
public static boolean solve(boolean[][] maze) {
int maxY = maze.length-1;
int maxX = maze[0].length-1;
int[] end = new int[]{maxY, maxX};
int[] currentPosition = new int[]{0, 0};
Stack<int[]> lastPosition = new Stack<>();
lastPosition.push(currentPosition);
while ( (currentPosition[0] != end[0] || currentPosition[1] != end[1])
&& !lastPosition.isEmpty()) {
// get current position coordinates
int y = currentPosition[0];
int x = currentPosition[1];
// Try moving right
if(x+1 <= maxX && maze[y][x+1]) {
currentPosition = new int[]{y,x+1}; // Move one step right
lastPosition.push(currentPosition);
} else if(y+1 <= maxY && maze[y+1][x]) { // Try moving down
currentPosition = new int[]{y+1,x}; // Move one step down
lastPosition.push(currentPosition);
} else {
maze[y][x] = false; // Mark as dead end (so we will not try to reach here again)
currentPosition = lastPosition.pop();
}
}
return !lastPosition.isEmpty();
}
It looks like it works well (I tested it against several mazes to make sure), it should also run in O(rc) time at worst case (which is fine for the a maze of rc size) but everything else I've seen uses recursion or other methods to solve this problem. Am I missing something?
Will appreciate any kind of guidance.