Rat in a Maze Problem I
Problem
Section titled “Problem”Consider a rat placed at (0, 0) in a square matrix of order N * N. It has to reach the destination at (N - 1, N - 1). Find all possible paths that the rat can take to reach from source to destination. The directions in which the rat can move are 'U'(up), 'D'(down), 'L' (left), 'R' (right). Value 0 at a cell in the matrix represents that it is blocked and rat cannot move to it while value 1 at a cell in the matrix represents that rat can be travel through it.
Note: In a path, no cell can be visited more than one time. If the source cell is 0, the rat cannot move to any other cell.
Solution approach
Section titled “Solution approach”Intuition
Section titled “Intuition”We need every path from (0, 0) to (N - 1, N - 1) that never visits a cell twice, so backtracking is the natural fit. From the current cell, try each open neighbour, recurse, and then undo the move. Blocking the current cell before moving away stops a path from coming back through it.
Algorithm
Section titled “Algorithm”- Copy the input into
maze, storen, and startcompute(0, 0)only if the source cell is open. - In
compute(i, j), if(i, j)is the destination, push the move stringsintoansand return. - Otherwise try the four moves in the order
'U','L','D','R'. For each one whose target is inside the grid and open:- Set
maze[i][j] = 0to block the current cell, and append the move letter tos. - Recurse into the neighbour.
- Pop the letter and set
maze[i][j] = 1to backtrack.
- Set
- Return
ans.
Complexity
Section titled “Complexity”- Time: in the worst case — a path can cover up to cells, and from each cell at most three directions are new, since the one we came from is blocked.
- Space: — the copy of
mazeand a recursion stack (and strings) up to deep, not counting the output.
Edge cases
Section titled “Edge cases”- Blocked source,
m[0][0] == 0:computeis never called, so the answer is empty. - Blocked destination: no move ever enters it, so the answer is empty.
class Solution { vector<vector<int>> maze; vector<string> ans; string s; int n;
public: void compute(int i, int j) { if (i == n - 1 && j == n - 1) { ans.push_back(s); return; }
if (i > 0 && maze[i - 1][j]) { maze[i][j] = 0; s.push_back('U'); compute(i - 1, j); s.pop_back(); maze[i][j] = 1; }
if (j > 0 && maze[i][j - 1]) { maze[i][j] = 0; s.push_back('L'); compute(i, j - 1); s.pop_back(); maze[i][j] = 1; }
if (i < n - 1 && maze[i + 1][j]) { maze[i][j] = 0; s.push_back('D'); compute(i + 1, j); s.pop_back(); maze[i][j] = 1; }
if (j < n - 1 && maze[i][j + 1]) { maze[i][j] = 0; s.push_back('R'); compute(i, j + 1); s.pop_back(); maze[i][j] = 1; } }
vector<string> findPath(vector<vector<int>> &m, int n) { this->n = n; this->maze = m; s = ""; this->n = n; if (maze[0][0]) compute(0, 0); return ans; }};Give it a try first
Attempt the problem on GeeksforGeeks — the code will still be here.