Rat in a Maze Problem in DSA C# - Time & Space Complexity
We want to understand how the time needed to solve the Rat in a Maze problem changes as the maze size grows.
Specifically, how does the search for a path through the maze take longer with bigger mazes?
Analyze the time complexity of the following code snippet.
bool SolveMaze(int[,] maze, int x, int y, int n) {
if (x == n - 1 && y == n - 1) return true;
if (IsSafe(maze, x, y, n)) {
maze[x, y] = 2; // mark path
if (SolveMaze(maze, x + 1, y, n)) return true;
if (SolveMaze(maze, x, y + 1, n)) return true;
maze[x, y] = 0; // backtrack
}
return false;
}
This code tries to find a path from the top-left to the bottom-right of a maze using backtracking.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Recursive calls exploring each cell in the maze.
- How many times: Potentially every cell is visited multiple times during backtracking.
As the maze size (n x n) grows, the number of possible paths grows very fast because the rat can move in multiple directions at each step.
| Input Size (n) | Approx. Operations |
|---|---|
| 2 | Few recursive calls, quick to find path or fail. |
| 4 | Many more paths to explore, operations increase quickly. |
| 8 | Operations grow very large due to many possible paths. |
Pattern observation: The time grows very fast, much faster than just doubling the maze size.
Time Complexity: O(2^(n*n))
This means the time needed can double for every new cell added, making it very slow for big mazes.
[X] Wrong: "The algorithm only checks each cell once, so it runs in linear time."
[OK] Correct: Because the rat tries many paths and backtracks, cells can be visited many times, causing exponential growth.
Understanding this problem helps you think about how recursive backtracking explores many possibilities, a skill useful in many coding challenges.
"What if we added memoization to remember visited paths? How would the time complexity change?"
Practice
Rat in a Maze problem?Solution
Step 1: Understand the problem statement
The Rat in a Maze problem requires finding a path from the start point (usually top-left) to the destination (usually bottom-right) in a maze represented by a grid.Step 2: Identify the goal
The goal is to find any valid path through open cells (usually marked as 1) avoiding blocked cells (marked as 0).Final Answer:
Find a path from the start to the destination in a maze -> Option AQuick Check:
Goal = Find path [OK]
- Thinking it's about counting walls
- Confusing with shortest path calculation
- Assuming the maze needs to be filled
Solution
Step 1: Check parameter types for maze and solution
In C#, 2D arrays are declared asint[,]. Options A, B, and D use incorrect types like jagged arrays or lists without proper syntax.Step 2: Check return type and parameters
The recursive function should returnboolto indicate success or failure, matching bool SolveMaze(int[,] maze, int x, int y, int[,] solution).Final Answer:
bool SolveMaze(int[,] maze, int x, int y, int[,] solution) -> Option AQuick Check:
Correct signature uses int[,] and bool return [OK]
- Using jagged arrays without proper syntax
- Using List<int> instead of arrays
- Wrong return type for recursion
int[,] maze = { {1, 1}, {1, 1} };
int[,] solution = new int[2,2];
bool result = SolveMaze(maze, 0, 0, solution);
if (result) {
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
Console.Write(solution[i,j] + " ");
}
Console.WriteLine();
}
} else {
Console.WriteLine("No path found");
}Solution
Step 1: Understand the maze and solution initialization
The maze is 2x2 with all cells open (1). The solution array is initially all zeros.Step 2: Trace the SolveMaze function
The rat starts at (0,0), marks it as 1 in solution, moves right to (0,1), marks it as 1, then moves down to (1,1) which is the destination. The path is (0,0) -> (0,1) -> (1,1). The cell (1,0) remains 0.Final Answer:
1 1 0 1 -> Option BQuick Check:
Path marks correct cells as 1 [OK]
- Assuming all cells in solution become 1
- Confusing row and column indices
- Printing 'No path found' incorrectly
bool SolveMaze(int[,] maze, int x, int y, int[,] solution) {
if (x == maze.GetLength(0) || y == maze.GetLength(1)) return false;
if (maze[x, y] == 0) return false;
solution[x, y] = 1;
if (x == maze.GetLength(0) - 1 && y == maze.GetLength(1) - 1) return true;
if (SolveMaze(maze, x + 1, y, solution)) return true;
if (SolveMaze(maze, x, y + 1, solution)) return true;
solution[x, y] = 0;
return false;
}Solution
Step 1: Analyze boundary condition
The conditionif (x == maze.GetLength(0) || y == maze.GetLength(1))only checks equality, but if x or y exceed bounds, it causes out-of-range errors. It should use '>=' to prevent this.Step 2: Check other parts
Solution array updates and base case are correct. Recursive calls explore right and down directions properly.Final Answer:
Boundary check uses '==' instead of '>=' causing out-of-bounds error -> Option CQuick Check:
Boundary check must prevent index overflow [OK]
- Using '==' instead of '>=' in boundary checks
- Forgetting to reset solution cell on backtrack
- Missing base case for destination
int[,] maze = {
{1, 0, 0, 0},
{1, 1, 0, 1},
{0, 1, 0, 0},
{1, 1, 1, 1}
};
Choose the correct solution matrix after the rat finds a path.Solution
Step 1: Trace the rat's moves trying right first, then down
Start at (0,0), mark 1, right (0,1)=0 blocked, down (1,0)=1 mark 1. From (1,0), right (1,1)=1 mark 1. From (1,1), right (1,2)=0 blocked, down (2,1)=1 mark 1. From (2,1), right (2,2)=0 blocked, down (3,1)=1 mark 1. From (3,1), right (3,2)=1 mark 1. From (3,2), right (3,3)=1 mark 1, destination.Step 2: Mark the path in solution matrix
Cells marked 1 are (0,0), (1,0), (1,1), (2,1), (3,1), (3,2), (3,3). Others remain 0.Final Answer:
1 0 0 0 1 1 0 0 0 1 0 0 0 1 1 1 -> Option DQuick Check:
Right-first path marks correct cells [OK]
- Marking blocked cells as path
- Incorrect backtracking
- Confusing row and column indices
Ready to prove it?
Pass the test and this pattern moves unknown
