Bird
Raised Fist0
DSA Typescriptprogramming~10 mins

Rat in a Maze Problem in DSA Typescript - Execution Trace

Choose your learning style10 modes available
Concept Flow - Rat in a Maze Problem
Start at (0,0)
↓
Check if current cell is safe
Yes↓
Mark cell as part of path
↓
Move Right
→Move Down
↓
If path found
No↓
Backtrack: Unmark cell
↓
Return False if no moves possible
↓
Goal reached at (N-1,N-1)
↓
Return True - path found
The rat starts at the top-left cell and tries to move right or down if the cell is safe. It marks the path and backtracks if stuck, until it reaches the goal.
Execution Sample
DSA Typescript
function solveMaze(maze: number[][], x: number, y: number, path: number[][]): boolean {
  const N = maze.length;
  if (x === N - 1 && y === N - 1) {
    path[x][y] = 1;
    return true;
  }
  if (x >= 0 && y >= 0 && x < N && y < N && maze[x][y] === 1 && path[x][y] === 0) {
    path[x][y] = 1;
    if (solveMaze(maze, x + 1, y, path) || solveMaze(maze, x, y + 1, path)) {
      return true;
    }
    path[x][y] = 0;
  }
  return false;
}
This recursive function tries to find a path from top-left to bottom-right by moving right or down in a safe maze.
Execution Table
StepCurrent Position (x,y)Is Safe?ActionPath Matrix State
1(0,0)YesMark (0,0), Move Right[[1,0,0],[0,0,0],[0,0,0]]
2(1,0)YesMark (1,0), Move Right[[1,0,0],[1,0,0],[0,0,0]]
3(2,0)NoBacktrack (2,0)[[1,0,0],[1,0,0],[0,0,0]]
4(1,1)YesMark (1,1), Move Right[[1,0,0],[1,1,0],[0,0,0]]
5(1,2)YesMark (1,2), Move Right[[1,0,0],[1,1,1],[0,0,0]]
6(2,2)YesMark (2,2), Goal Reached[[1,0,0],[1,1,1],[0,0,1]]
7Return True-Path Found[[1,0,0],[1,1,1],[0,0,1]]
💡 Goal reached at (2,2), path found successfully.
Variable Tracker
VariableStartAfter Step 1After Step 2After Step 3After Step 4After Step 5After Step 6Final
x012Backtrack to 11122
y000Backtrack to 11222
path[[0,0,0],[0,0,0],[0,0,0]][[1,0,0],[0,0,0],[0,0,0]][[1,0,0],[1,0,0],[0,0,0]][[1,0,0],[1,0,0],[0,0,0]][[1,0,0],[1,1,0],[0,0,0]][[1,0,0],[1,1,1],[0,0,0]][[1,0,0],[1,1,1],[0,0,1]][[1,0,0],[1,1,1],[0,0,1]]
Key Moments - 3 Insights
Why do we backtrack and unmark a cell in the path?
When both moving right and down from a cell fail to find the goal (see Step 3), we remove the mark to indicate this cell is not part of the correct path, allowing other paths to be explored.
How do we know when the goal is reached?
At Step 6, when the current position is (2,2) which is the bottom-right cell, the function marks it and returns true, signaling the path is complete.
Why do we check if the cell is safe before moving?
Only cells with value 1 are safe to move into. This check prevents moving into blocked cells (like at Step 3 where (2,0) is unsafe).
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the path matrix state after Step 4?
A[[1,0,0],[1,1,0],[0,0,0]]
B[[1,0,0],[1,0,0],[0,0,0]]
C[[1,0,0],[0,0,0],[0,0,0]]
D[[1,0,0],[1,1,1],[0,0,0]]
💡 Hint
Check the 'Path Matrix State' column for Step 4 in the execution table.
At which step does the algorithm backtrack due to an unsafe cell?
AStep 2
BStep 3
CStep 5
DStep 6
💡 Hint
Look for the step where the action says 'Backtrack' in the execution table.
If the maze had a blocked cell at (1,2), what would happen at Step 5?
AThe algorithm would skip (1,2) and move down
BThe algorithm would mark (1,2) and continue
CThe algorithm would backtrack from (1,2)
DThe algorithm would immediately find the goal
💡 Hint
Refer to the safety check and backtracking logic shown in the execution table and variable tracker.
Concept Snapshot
Rat in a Maze Problem:
- Start at top-left cell (0,0)
- Move only right or down to safe cells (value 1)
- Mark path cells as part of solution
- Backtrack if stuck by unmarking
- Stop when bottom-right cell is reached
- Recursive DFS approach
Full Transcript
The Rat in a Maze problem involves finding a path from the top-left corner to the bottom-right corner of a grid maze. The rat can move only right or down into safe cells marked with 1. The algorithm marks each cell it visits as part of the path. If it reaches a dead end, it backtracks by unmarking the cell and tries other directions. This process continues recursively until the goal cell is reached or no path exists. The execution table shows each step, the current position, safety check, actions taken, and the path matrix state. Key moments include understanding backtracking, recognizing the goal, and checking cell safety. The visual quiz tests understanding of path states, backtracking steps, and behavior when cells are blocked.

Practice

(1/5)
1. What is the main goal of the Rat in a Maze Problem in data structures and algorithms?
easy
A. Sort the cells of the maze in ascending order
B. Count the number of walls in the maze
C. Calculate the shortest distance between two points in a graph
D. Find a path from the start to the destination in a maze

Solution

  1. Step 1: Understand the problem context

    The Rat in a Maze problem involves navigating through a maze represented as a grid to find a path from the start cell to the destination cell.
  2. Step 2: Identify the goal

    The goal is to find a valid path that the rat can follow to reach the destination without crossing walls or blocked cells.
  3. Final Answer:

    Find a path from the start to the destination in a maze -> Option D
  4. Quick Check:

    Goal = Find path [OK]
Hint: Remember: Rat must find a path, not count or sort cells [OK]
Common Mistakes:
  • Confusing path finding with counting walls
  • Thinking the problem is about sorting cells
  • Assuming shortest path is always required
2. Which of the following is the correct TypeScript syntax to declare a 2D maze array of size 4x4 filled with zeros?
easy
A. const maze: number[][] = Array.from({length: 4}, () => Array(4).fill(0));
B. const maze: number[][] = [[0]*4]*4;
C. const maze: number[][] = new Array(4, 4).fill(0);
D. const maze: number[][] = Array(4).fill(Array(4).fill(0));

Solution

  1. Step 1: Understand array initialization in TypeScript

    Using Array.from with a mapping function creates independent inner arrays, avoiding reference issues.
  2. Step 2: Analyze each option

    const maze: number[][] = Array(4).fill(Array(4).fill(0)); creates inner arrays by reference, causing all rows to point to the same array. const maze: number[][] = Array.from({length: 4}, () => Array(4).fill(0)); correctly creates separate arrays for each row. Options B and C use invalid syntax for 2D arrays.
  3. Final Answer:

    const maze: number[][] = Array.from({length: 4}, () => Array(4).fill(0)); -> Option A
  4. Quick Check:

    Correct 2D array init = const maze: number[][] = Array.from({length: 4}, () => Array(4).fill(0)); [OK]
Hint: Use Array.from with a function to avoid shared references [OK]
Common Mistakes:
  • Using fill with nested arrays causing shared references
  • Incorrect syntax for 2D array creation
  • Confusing array size parameters
3. Given the following maze and code snippet, what will be the output?
const maze = [
  [1, 0, 0, 0],
  [1, 1, 0, 1],
  [0, 1, 0, 0],
  [1, 1, 1, 1]
];

function isSafe(x: number, y: number): boolean {
  return x >= 0 && y >= 0 && x < 4 && y < 4 && maze[x][y] === 1;
}

function solveMaze(x: number, y: number, path: string[]): boolean {
  if (x === 3 && y === 3) {
    path.push(`(${x},${y})`);
    return true;
  }
  if (isSafe(x, y)) {
    path.push(`(${x},${y})`);
    if (solveMaze(x + 1, y, path)) return true;
    if (solveMaze(x, y + 1, path)) return true;
    path.pop();
  }
  return false;
}

const path: string[] = [];
if (solveMaze(0, 0, path)) {
  console.log(path.join(' -> '));
} else {
  console.log('No path found');
}
medium
A. (0,0) -> (0,1) -> (1,1) -> (2,1) -> (3,1) -> (3,2) -> (3,3)
B. (0,0) -> (1,0) -> (1,1) -> (2,1) -> (3,1) -> (3,2) -> (3,3)
C. No path found
D. (0,0) -> (1,0) -> (2,0) -> (3,0) -> (3,1) -> (3,2) -> (3,3)

Solution

  1. Step 1: Trace the recursive path from (0,0)

    Starting at (0,0), the rat moves down to (1,0) since maze[1][0] = 1. Then right to (1,1), down to (2,1), down to (3,1), right to (3,2), and right to (3,3).
  2. Step 2: Verify path validity and output

    All these cells are safe (value 1). The path is recorded and printed as shown in (0,0) -> (1,0) -> (1,1) -> (2,1) -> (3,1) -> (3,2) -> (3,3).
  3. Final Answer:

    (0,0) -> (1,0) -> (1,1) -> (2,1) -> (3,1) -> (3,2) -> (3,3) -> Option B
  4. Quick Check:

    Path found = (0,0) -> (1,0) -> (1,1) -> (2,1) -> (3,1) -> (3,2) -> (3,3) [OK]
Hint: Follow down then right moves recursively to find path [OK]
Common Mistakes:
  • Assuming movement to blocked cells (0 values)
  • Confusing row and column indices
  • Ignoring backtracking when path fails
4. Identify the bug in the following TypeScript code snippet for the Rat in a Maze problem:
function solveMaze(x: number, y: number, path: string[]): boolean {
  if (x === 3 && y === 3) {
    path.push(`(${x},${y})`);
    return true;
  }
  if (isSafe(x, y)) {
    path.push(`(${x},${y})`);
    if (solveMaze(x + 1, y, path)) return true;
    if (solveMaze(x, y + 1, path)) return true;
    path.pop();
  }
  return false;
}
medium
A. isSafe function is not called before pushing to path
B. Incorrect base case coordinates for destination
C. Missing backtracking step to remove current cell from path when dead end is reached
D. The function should move left and up instead of right and down

Solution

  1. Step 1: Analyze the recursion and path tracking

    The function adds the current cell to path but does not remove it if both recursive calls fail, causing incorrect path accumulation.
  2. Step 2: Identify missing backtracking

    Backtracking requires removing the current cell from path when no path forward is found, which is missing here.
  3. Final Answer:

    Missing backtracking step to remove current cell from path when dead end is reached -> Option C
  4. Quick Check:

    Backtracking needed = Missing backtracking step to remove current cell from path when dead end is reached [OK]
Hint: Always pop path on dead ends to backtrack [OK]
Common Mistakes:
  • Forgetting to remove cell from path on failure
  • Incorrect base case coordinates
  • Ignoring isSafe checks before path push
5. You want to modify the Rat in a Maze algorithm to find all possible paths from start (0,0) to destination (N-1,N-1) in an NxN maze. Which approach should you use?
hard
A. Use backtracking to explore all safe moves, storing each complete path separately
B. Stop at the first found path and return immediately
C. Use a greedy approach to always move right or down only
D. Convert the maze to a graph and use Dijkstra's algorithm to find shortest path

Solution

  1. Step 1: Understand the requirement to find all paths

    Finding all paths requires exploring every possible route without stopping at the first success.
  2. Step 2: Choose backtracking to explore all safe moves

    Backtracking allows exploring all safe moves recursively, storing each complete path separately before backtracking to try other routes.
  3. Final Answer:

    Use backtracking to explore all safe moves, storing each complete path separately -> Option A
  4. Quick Check:

    All paths = Backtracking exploration [OK]
Hint: Backtrack fully to find all paths, not just one [OK]
Common Mistakes:
  • Stopping after first path found
  • Using greedy moves that miss paths
  • Using shortest path algorithms instead of all paths
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard