Homework
Team Teach Homework
Maze Solver Problem
Instructions
Your task is to write a method solveMaze(char[][] maze, int startX, int startY) that determines whether a path exists from a starting point (startX, startY) in a 2D maze to the exit marked as 'E'. Use recursion to explore the maze.
Requirements
Input
- 
    
A 2D array of characters (
char[][] maze) representing the maze. - 
    
An integer
startXindicating the row index of the starting point. - 
    
An integer
startYindicating the column index of the starting point. 
Output
- 
    
Return
trueif there is a path from(startX, startY)to'E'. - 
    
Return
falseif no such path exists. 
Maze Rules
- 
    
' 'represents an open path (you can move here). - 
    
'#'represents a wall (you cannot move here). - 
    
'E'represents the exit (this is the destination). 
Movement
- 
    
You can move up, down, left, or right to adjacent cells.
 - 
    
You cannot move diagonally or leave the bounds of the maze.
 
Marking Visited Cells
- To avoid revisiting the same cells, mark visited cells as 
'#'temporarily during recursion. Restore them to' 'after backtracking. 
Steps to Solve
- 
    
Check if the current position is valid:
- 
        
Is it within the bounds of the maze?
 - 
        
Is it an open path or the exit?
 
 - 
        
 - 
    
Check if the current position is
'E'. If yes, returntrue. - 
    
Mark the current cell as visited (change it to
'#'). - 
    
Recursively explore all possible directions (up, down, left, right).
 - 
    
If any direction leads to the exit, return
true. - 
    
Restore the cell to
' 'after exploring (backtracking). - 
    
If no paths lead to the exit, return
false. 
Test Case 2: Starting at the Exit
char[][] maze = {
    {'#', '#', '#', '#', '#'},
    {'#', ' ', ' ', '#', 'E'},
    {'#', ' ', '#', ' ', '#'},
    {'#', ' ', ' ', ' ', '#'},
    {'#', '#', '#', '#', '#'}
};
System.out.println(solveMaze(maze, 1, 4)); // Output: true
HW
public static boolean solveMaze(char[][] maze, int x, int y) {
    if (x < 0 || y < 0 || x >= maze.length || y >= maze[0].length) {
        return false;
    }
    
    if (maze[x][y] == 'E') {
        return true;
    }
    
    if (maze[x][y] == '#' || maze[x][y] == 'V') {
        return false;
    }
    
    maze[x][y] = 'V';
    
    boolean result = solveMaze(maze, x + 1, y) || 
                     solveMaze(maze, x - 1, y) || 
                     solveMaze(maze, x, y + 1) || 
                     solveMaze(maze, x, y - 1);   
    
    maze[x][y] = ' ';
    
    return result;
}