Consider a rat placed at (0, 0) in a square matrix m[ ][ ] of order n and has to reach the destination at (n-1, n-1). The task is to find a sorted array of strings denoting all the possible directions which the rat can take to reach the destination at (n-1, n-1). The directions in which the rat can move are ‘U'(up), ‘D'(down), ‘L’ (left), ‘R’ (right).
Input : N = 4
1 0 0 0
1 1 0 1
0 1 0 0
0 1 1 1
On following the path DRDDRR ,the rat can reach the bottom right of the maze.
Input :N = 4
1 0 0 0
1 1 0 1
1 1 0 0
0 1 1 1
- Start from the initial index (i.e. (0,0)) and look for the valid moves through the adjacent cells in the order Down->Left->Right->Up (so as to get the sorted paths) in the grid.
- If the move is possible, then move to that cell while storing the character corresponding to the move(D,L,R,U) and again start looking for the valid move until the last index (i.e. (n-1,n-1)) is reached.
- Also, keep on marking the cells as visited and when we traversed all the paths possible from that cell, then unmark that cell for other different paths and remove the character from the path formed.
- As the last index of the grid(bottom right) is reached, then store the traversed path.
Below is the implementation of the above approach
DDRRURRDDD DDRURRRDDD DRDRURRDDD DRRRRDDD
GeeksforGeeks has prepared a complete interview preparation course with premium videos, theory, practice problems, TA support and many more features. Please refer Placement 100 for details
- Rat in a Maze with multiple steps or jump allowed
- A variation of Rat in a Maze : multiple steps or jumps allowed
- Find single Movement in a Matrix
- Maze With N doors and 1 Key
- Rat in a Maze | Backtracking-2
- Rat in a Maze | Backtracking using Stack
- Shortest path in a Binary Maze
- Count number of ways to reach destination in a Maze
- Count number of ways to reach destination in a Maze using BFS
- Count number of ways to reach destination in a maze
- Find paths from corner cell to middle cell in maze
- Find the largest rectangle of 1's with swapping of columns allowed
- Maximum points collected by two persons allowed to meet once
- Minimum cost to reach a point N from 0 with two different operations allowed
- Find maximum path sum in a 2D matrix when exactly two left moves are allowed