Home
DSA Course
Backtracking
Rat in a Maze
Rat in a Maze
Given a N*N maze with some obstacles, starting from the top-left corner, finding a path to reach the bottom-right corner.
Rat in a Maze
Ready
See the Logic in Motion
Stop memorizing code. Unlock the full interactive visualizer to master the logic step-by-step.Intuition
Imagine a rat starts at the source and wants to reach the destination. The rat can move in four directions: up, down, left, right. It cannot move to a blocked cell or a cell it has already visited in the current path. If it hits a dead end, it backtracks.
Concept
Key Concepts:
- Grid Traversal: Moving through a 2D array.
- State Management: Keeping track of visited cells to avoid cycles.
- Backtracking: Exploring a path, and if it fails, undoing the last move to try a different direction.
- Directions: Typically Down, Right, Up, Left (lexicographical order if required).
How it Works
- Start at (0, 0).
- Mark the current cell as part of the solution path.
- Try moving in allowed directions (e.g., D, L, R, U).
- Check if the next cell is safe (within bounds, open, not visited).
- If safe, recursively jump to that cell.
- If the recursion returns true (destination found), propagate true up.
- If all directions fail, unmark the current cell (backtrack) and return false.
Step-by-Step Breakdown
Example 3x3 Maze:
- Start (0,0). Valid. Path: [(0,0)]
- Try Down (1,0): Wall.
- Try Right (0,1): Valid. Path: [(0,0), (0,1)]
- From (0,1), Try Down (1,1): Valid. Path: ...
- Continue until (N-1, N-1) is reached.
- If stuck, remove last cell from path and try next direction.
When to Use
- Pathfinding in grids with obstacles.
- Generating all possible paths in a maze.
- Robotics path planning (basic).
When NOT to Use
- Finding the shortest path in an unweighted graph (use BFS).
- Large open grids where A* or other heuristic search is more efficient.
How to Identify
"Find path in a grid", "Maze", "Rat", "Reach destination".
Stop Guessing, Start Mastering.
Build the FAANG intuition. Master this pattern with optimized implementations, visual dry runs, and our curated collection of high-yield problems.
