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
- 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
- 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 using BFS
- Count number of ways to reach destination in a Maze
- 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
- Minimum Cost Path with Left, Right, Bottom and Up moves allowed
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.