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
- 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 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
- Minimum cost to reach a point N from 0 with two different operations allowed
- Find the largest rectangle of 1's with swapping of columns allowed
- Maximum points collected by two persons allowed to meet once
- Print all paths from top left to bottom right in a matrix with four 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 email@example.com. 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.