In this video I have this question i.e. rat in a maze which is based on recursion & backtracking concept.
This a backtracking solution to find all possible paths from the top-left corner to the bottom-right corner of a grid (matrix) where movement is allowed only through cells marked as 1 (indicating valid paths). The function solve recursively explores all possible directions (up, down, right) from the current cell, constructing a string that represents the path taken. The recursion backtracks by marking cells as visited (setting them to 0) to avoid cycles, and it restores the cell's state upon backtracking.
Input Validation: The algorithm first checks if the starting cell (top-left corner) is valid (i.e., not blocked). If it is blocked, it returns -1.
Recursive Exploration: The solve function is called recursively to explore all valid moves from the current position (i, j):
Base Case: If the current position is the bottom-right corner, the current path string is added to the results.
Invalid Moves: If the current position is out of bounds or a blocked cell (i.e., 0), the function returns without doing anything.
The current cell is marked as visited by setting mat[i][j] to 0.
The function recursively calls itself for the four possible moves (up, down, right).
After exploring all possible moves, the cell is unmarked (set back to 1) to allow other paths to use it.
Note: Either you can do changes in the matrix itself like done in this question OR you can take a visited array and then mark and unmark the cells visited during the function call and after the function call.
Result Compilation: After all recursive calls complete, the function returns a vector of all valid paths found.
TC: O(4^(N*N))
SC: O(L*X)
Note: If you have done this question you can try this question also- Word Search 😎
#datastructure #leetcode #gfg #gfgpotd #gfgsolutions #datastructure #programming #leetcodeproblems #education #computerscience #engineering #btech #btechjobs #problemsolving
Негізгі бет Rat in a Maze | GFG | C++ Solution Recursion & Backtracking
Пікірлер: 5