Question: How does the following function do the recursive backtracking? What is the base case for this function? Let's say that the function is try to

How does the following function do the recursive backtracking? What is the base case for this function?

Let's say that the function is try to generate a maze, start from a point and move 2 cells everytime.

If it starts from (3,5), -> (5,5) -> (5,7) -> (7,7), then it hits dead end. How does it backtrack to last path?

public void recursion(int r, int c) { // 4 random directions int[] randDirs = generateRandomDirections(); // Examine each direction for (int i = 0; i < randDirs.length; i++) { switch(randDirs[i]){ case 1: // Up //Whether 2 cells up is out or not if (r - 2 <= 0) continue; if (maze[r - 2][c] != 0) { maze[r-2][c] = 0; maze[r-1][c] = 0; recursion(r - 2, c); } break; case 2: // Right // Whether 2 cells to the right is out or not if (c + 2 >= width - 1) continue; if (maze[r][c + 2] != 0) { maze[r][c + 2] = 0; maze[r][c + 1] = 0; recursion(r, c + 2); } break; case 3: // Down // Whether 2 cells down is out or not if (r + 2 >= height - 1) continue; if (maze[r + 2][c] != 0) { maze[r+2][c] = 0; maze[r+1][c] = 0; recursion(r + 2, c); } break; case 4: // Left // Whether 2 cells to the left is out or not if (c - 2 <= 0) continue; if (maze[r][c - 2] != 0) { maze[r][c - 2] = 0; maze[r][c - 1] = 0; recursion(r, c - 2); } break; } } } 

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!