Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • DSA
  • Practice Backtracking
  • Interview Problems on Backtracking
  • MCQs on Backtracking
  • Tutorial on Backtracking
  • Backtracking vs Recursion
  • Backtracking vs Branch & Bound
  • Print Permutations
  • Subset Sum Problem
  • N-Queen Problem
  • Knight's Tour
  • Sudoku Solver
  • Rat in Maze
  • Hamiltonian Cycle
  • Graph Coloring
Open In App
Next Article:
Rat in a Maze Problem when movement in all possible directions is allowed
Next article icon

Rat in a Maze Problem when movement in all possible directions is allowed

Last Updated : 15 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report
Try it on GfG Practice
redirect icon

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).

Examples: 

Input : N = 4 
1 0 0 0 
1 1 0 1 
0 1 0 0 
0 1 1 1
Output :
DRDDRR

Input :N = 4 
1 0 0 0 
1 1 0 1 
1 1 0 0 
0 1 1 1
Output :
DDRDRR DRDDRR
Explanation: 

Solution: 

Brute Force Approach:

We can use simple backtracking without using any extra space .

C++
// C++ implementation of the above approach #include <bits/stdc++.h> #define MAX 5 using namespace std;           void getallpath(int matrix[MAX][MAX], int n,int row,int col,vector<string> &ans,string cur)     {         if(row>=n or col>=n or row<0 or col<0 or matrix[row][col] == 0)         return ;                  if(row == n-1 and col == n-1)         {             ans.push_back(cur);             return ;         }                  //now if its one we have 4 calls         matrix[row][col] = 0;                  getallpath(matrix,n,row-1,col,ans,cur+"U");         getallpath(matrix,n,row,col+1,ans,cur+"R");         getallpath(matrix,n,row,col-1,ans,cur+"L");         getallpath(matrix,n,row+1,col,ans,cur+"D");                  matrix[row][col] = 1;                  return ;     }      vector<string> findPath(int matrix[MAX][MAX], int n) {         // Your code goes here         vector<string> ans;         getallpath(matrix,n,0,0,ans,"");         return ans;     } int main() {     int m[MAX][MAX] = { { 1, 0, 0, 0, 0 },                         { 1, 1, 1, 1, 1 },                         { 1, 1, 1, 0, 1 },                         { 0, 0, 0, 0, 1 },                         { 0, 0, 0, 0, 1 } };     int n = sizeof(m) / sizeof(m[0]);     vector<string> ans = findPath(m, n);     for(auto i : ans)     cout<<i<<" ";      return 0; } 
Java
import java.util.*;  public class Main {     static final int MAX = 5;      static void getallpath(int[][] matrix, int n, int row,                            int col, List<String> ans,                            String cur)     {         if (row >= n || col >= n || row < 0 || col < 0             || matrix[row][col] == 0) {             return;         }          if (row == n - 1 && col == n - 1) {             ans.add(cur);             return;         }          matrix[row][col] = 0;          getallpath(matrix, n, row - 1, col, ans, cur + "U");         getallpath(matrix, n, row, col + 1, ans, cur + "R");         getallpath(matrix, n, row, col - 1, ans, cur + "L");         getallpath(matrix, n, row + 1, col, ans, cur + "D");          matrix[row][col] = 1;          return;     }      static List<String> findPath(int[][] matrix, int n)     {         List<String> ans = new ArrayList<>();         getallpath(matrix, n, 0, 0, ans, "");         return ans;     }      public static void main(String[] args)     {         int[][] m = { { 1, 0, 0, 0, 0 },                       { 1, 1, 1, 1, 1 },                       { 1, 1, 1, 0, 1 },                       { 0, 0, 0, 0, 1 },                       { 0, 0, 0, 0, 1 } };         int n = m.length;         List<String> ans = findPath(m, n);         for (String i : ans) {             System.out.println(i + " ");         }     } }  // This code is contributed by abn95knd1. 
Python
# Python3 implementation of the above approach def getallpath(mat, n, ans, curpath, r, c):         if(r>=n or c>=n or r<0 or c<0 or mat[r][c] == 0):             return;                  if(r == n-1 and c == n-1):             ans.append(curpath)             return         mat[r][c] = 0                  # calls         getallpath(mat,n,ans,curpath+"U",r-1,c)         getallpath(mat,n,ans,curpath+"D",r+1,c)         getallpath(mat,n,ans,curpath+"L",r,c-1)         getallpath(mat,n,ans,curpath+"R",r,c+1)                  mat[r][c] = 1;  # Function to store and print # all the valid paths def findpath(mat ,n):      # vector to store all the possible paths     possiblePaths = []     getallpath(mat,n,possiblePaths,"",0,0)     # Print all possible paths     for i in range(len(possiblePaths)):         print(possiblePaths[i], end = " ")  # Driver code if __name__ == "__main__":          mat = [ [ 1, 0, 0, 0, 0 ],            [ 1, 1, 1, 1, 1 ],            [ 1, 1, 1, 0, 1 ],            [ 0, 0, 0, 0, 1 ],           [ 0, 0, 0, 0, 1 ] ]     n = len(mat)          findpath(mat, n)  # This code is contributed by Arpit Jain 
C#
using System; using System.Collections.Generic;  namespace Algorithm {     class MainClass     {         static readonly int MAX = 5;          static void getallpath(int[,] matrix, int n, int row,                                int col, List<string> ans,                                string cur)         {             if (row >= n || col >= n || row < 0 || col < 0                 || matrix[row, col] == 0)             {                 return;             }              if (row == n - 1 && col == n - 1)             {                 ans.Add(cur);                 return;             }              matrix[row, col] = 0;              getallpath(matrix, n, row - 1, col, ans, cur + "U");             getallpath(matrix, n, row, col + 1, ans, cur + "R");             getallpath(matrix, n, row, col - 1, ans, cur + "L");             getallpath(matrix, n, row + 1, col, ans, cur + "D");              matrix[row, col] = 1;              return;         }          static List<string> findPath(int[,] matrix, int n)         {             List<string> ans = new List<string>();             getallpath(matrix, n, 0, 0, ans, "");             return ans;         }          public static void Main(string[] args)         {             int[,] m = { { 1, 0, 0, 0, 0 },                          { 1, 1, 1, 1, 1 },                          { 1, 1, 1, 0, 1 },                          { 0, 0, 0, 0, 1 },                          { 0, 0, 0, 0, 1 } };             int n = m.GetLength(0);             List<string> ans = findPath(m, n);             foreach (string i in ans)             {                 Console.Write(i + " ");             }         }     } } 
JavaScript
// The equivalent JavaScript code is as follows:  const MAX = 5;  function getallpath(matrix, n, row, col, ans, cur) {   if (row >= n || col >= n || row < 0 || col < 0 || matrix[row][col] === 0) {     return;   }    if (row === n - 1 && col === n - 1) {     ans.push(cur);     return;   }    matrix[row][col] = 0;    getallpath(matrix, n, row - 1, col, ans, cur + "U");   getallpath(matrix, n, row, col + 1, ans, cur + "R");   getallpath(matrix, n, row, col - 1, ans, cur + "L");   getallpath(matrix, n, row + 1, col, ans, cur + "D");    matrix[row][col] = 1;    return; }  function findPath(matrix, n) {   let ans = [];   getallpath(matrix, n, 0, 0, ans, "");   return ans; }  let m = [   [1, 0, 0, 0, 0],   [1, 1, 1, 1, 1],   [1, 1, 1, 0, 1],   [0, 0, 0, 0, 1],   [0, 0, 0, 0, 1], ]; let n = m.length; let ans = findPath(m, n); for (let i of ans) {   console.log(i + " "); } 

Output
DRRRRDDD DRDRURRDDD DDRURRRDDD DDRRURRDDD  

Complexity Analysis: 

Time Complexity: O(3^(n^2))
As we are making 4 calls for every cell in the matrix.
Auxiliary Space: O(1)
As we are not using any extra space.



Next Article
Rat in a Maze Problem when movement in all possible directions is allowed

R

Rishav Saxena
Improve
Article Tags :
  • Backtracking
  • Matrix
  • C++ Programs
  • DSA
Practice Tags :
  • Backtracking
  • Matrix

Similar Reads

    A variation of Rat in a Maze : multiple steps or jumps allowed
    A variation of rat in a maze. You are given an N * N 2-D matrix shaped maze (let's call it M), there is a rat in the top-left cell i.e. M[0][0] and there is an escape door in the bottom-right cell i.e. M[N-1][N-1]. From each cell M[i][j] (0 ? i ? N-1, 0 ? j ? N-1) the rat can go a number of steps to
    15 min read
    Rat and Poisoned bottle Problem
    Given N number of bottles in which one bottle is poisoned. So the task is to find out the minimum number of rats required to identify the poisoned bottle. A rat can drink any number of bottles at a time and if any of the taken bottles is poisonous, then the rat dies and cannot drink anymore.Examples
    4 min read
    Check if it is possible to travel all points in given time by moving in adjacent four directions
    Given 3 arrays X[], Y[], and T[] all of the size N where X[i] and Y[i] represent the i-th coordinate and T[i] represents the time in seconds. Find it is possible to reach all the coordinates (X[i], Y[i]) in time T[i] from starting coordinates (0, 0). The pointer can move in four directions ( x +1, y
    13 min read
    Rat in a Maze with multiple steps or jump allowed
    You are given an n × n maze represented as a matrix. The rat starts from the top-left corner (mat[0][0]) and must reach the bottom-right corner (mat[n-1][n-1]).The rat can move forward (right) or downward.A 0 in the matrix represents a dead end, meaning the rat cannot step on that cell.A non-zero va
    11 min read
    Find cells in Matrix that are not visited by Robot for given movements
    Given an integer N, which denotes the size of the matrix that is N*N. There is a robot placed over the top-left corner (0, 0) of the matrix, the direction of movement of the robot are given as (N, S, W, E, NE, NW, SE, SW which denotes North, South, West, East, North-East, North-west, South-east, Sou
    15+ min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences