Complete the code to check if the rat can move to the next cell inside the maze boundaries.
boolean isSafe(int x, int y, int N) {
return (x >= 0 && y >= 0 && x < [1] && y < N);
}The maze size is N x N, so the valid indices are from 0 to N-1. We check if x and y are less than N to stay inside the maze.
Complete the code to mark the current cell as part of the solution path.
void solveMazeUtil(int maze[][], int x, int y, int sol[][], int N) {
if (x == N - 1 && y == N - 1) {
sol[x][y] = [1];
return;
}
}We mark the cell as 1 to indicate it is part of the solution path.
Fix the error in the recursive call to move right in the maze.
if (isSafe(x, y + 1, N) && maze[x][y + 1] == 1) { solveMazeUtil(maze, x, [1], sol, N); }
To move right, we increase the y coordinate by 1, so the recursive call should use y + 1.
Fill both blanks to move down and backtrack correctly in the maze.
if (isSafe(x + 1, y, N) && maze[x + 1][y] == 1) { solveMazeUtil(maze, [1], [2], sol, N); } sol[x][y] = 0; // backtrack
To move down, increase x by 1 and keep y the same. Backtracking resets the current cell to 0.
Fill all three blanks to complete the base case and recursive calls for the rat in a maze.
if (x == N - 1 && y == N - 1) { sol[x][y] = [1]; return true; } if (isSafe(x, y, N) && maze[x][y] == 1) { sol[x][y] = [2]; if (solveMazeUtil(maze, x + 1, y, sol, N)) return true; if (solveMazeUtil(maze, x, y + 1, sol, N)) return true; sol[x][y] = [3]; // backtrack } return false;
Mark the path with 1, and backtrack by resetting the cell to 0.
