0
0
DSA Cprogramming~3 mins

Why Rat in a Maze Problem in DSA C?

Choose your learning style9 modes available
The Big Idea

What if you could teach a computer to find its way out of any maze without getting lost?

The Scenario

Imagine you are in a big maze trying to find a path from the start to the exit. You try every turn by walking around, but it's easy to get lost or miss the right path.

The Problem

Manually exploring every path is slow and confusing. You might go in circles or miss the exit because you don't remember where you have been. It's hard to keep track of all possible routes without a clear plan.

The Solution

The Rat in a Maze problem uses a smart way to explore paths step-by-step, backtracking when hitting dead ends. This method remembers choices and tries alternatives until it finds the exit or proves none exists.

Before vs After
Before
int x = 0, y = 0;
while(not_exit) {
  if(can_move_right) x++;
  else if(can_move_down) y++;
  else break;
}
After
bool solveMaze(int maze[N][N], int x, int y, int sol[N][N]) {
  if(x == N-1 && y == N-1) {
    sol[x][y] = 1;
    return true;
  }
  if(isSafe(x, y)) {
    sol[x][y] = 1;
    if(solveMaze(maze, x+1, y, sol)) return true;
    if(solveMaze(maze, x, y+1, sol)) return true;
    if(solveMaze(maze, x-1, y, sol)) return true;
    if(solveMaze(maze, x, y-1, sol)) return true;
    sol[x][y] = 0;
  }
  return false;
}
What It Enables

This approach lets you find a path through complex mazes automatically, saving time and avoiding confusion.

Real Life Example

Robots navigating unknown buildings use similar logic to find safe paths without getting stuck.

Key Takeaways

Manual maze solving is slow and error-prone.

Backtracking explores all paths systematically.

It helps find a solution or prove none exists.