Rat in a Maze Problem - I | Practice | GeeksforGeeks

Consider a rat placed at (0, 0) in a square matrix of order N * N. It has to reach the destination at (N - 1, N - 1). Find all possible paths that the rat can take to reach from source to destination. The directions in which the rat can move are 'U'(up), 'D'(down), 'L' (left), 'R' (right). Value 0 at a cell in the matrix represents that it is blocked and rat cannot move to it while value 1 at a cell in the matrix represents that rat can be travel through it.
Note: In a path, no cell can be visited more than one time. If the source cell is 0, the rat cannot move to any other cell.
Example 1:
Input:
N = 4
m[][] = {{1, 0, 0, 0},
         {1, 1, 0, 1}, 
         {1, 1, 0, 0},
         {0, 1, 1, 1}}
Output:
DDRDRR DRDDRR
Explanation:
The rat can reach the destination at 
(3, 3) from (0, 0) by two paths - DRDDRR 
and DDRDRR, when printed in sorted order 
we get DDRDRR DRDDRR.
Input:
N = 2
m[][] = {{1, 0},
         {1, 0}}
Output:
-1
Explanation:
No path exists and destination cell is 
blocked.

Your Task:  
You don't need to read input or print anything. Complete the function printPath() which takes N and 2D array m[ ][ ] as input parameters and returns the list of paths in lexicographically increasing order. 
Note: In case of no path, return an empty list. The driver will output "-1" automatically.
Expected Time Complexity: O((3N^2)).
Expected Auxiliary Space: O(L * X), L = length of the path, X = number of paths.
Constraints:
2 ≤ N ≤ 5
0 ≤ m[i][j] ≤ 1
0
bhattpawan19973 hours ago
Please let m know why this solution is not passing:
 
// { Driver Code Starts// Initial Template for Java
import java.util.*;class Rat {   public static void main(String[] args) {       Scanner sc = new Scanner(System.in);       int t = sc.nextInt();
       while (t-- > 0) {           int n = sc.nextInt();           int[][] a = new int[n][n];           for (int i = 0; i < n; i++)               for (int j = 0; j < n; j++) a[i][j] = sc.nextInt();
           Solution obj = new Solution();           ArrayList<String> res = obj.findPath(a, n);           Collections.sort(res);           if (res.size() > 0) {               for (int i = 0; i < res.size(); i++)                   System.out.print(res.get(i) + " ");               System.out.println();           } else {               System.out.println(-1);           }       }   }}// } Driver Code Ends
// User function Template for Java
// m is the given matrix and n is the order of matrixclass Solution {      static ArrayList<String> res = new ArrayList<>();      private static void findPathHelper(int[][]m, int row, int col, int n, String path, boolean[][] visited){              if(row < 0 || col < 0 || row == n || col == n || m[row][col] == 0 || visited[row][col] == true){           return;       }              if(row == n-1 && col == n-1){           res.add(path);           return;       }              visited[row][col] = true;       findPathHelper(m,row+1,col,n,path+'D',visited);       findPathHelper(m,row,col-1,n,path+'L',visited);       findPathHelper(m,row,col+1,n,path+'R',visited);       findPathHelper(m,row-1,col,n,path+'U',visited);       visited[row][col] = false;   }      public static ArrayList<String> findPath(int[][] m, int n) {              boolean[][] visited = new boolean[n][n];              findPathHelper(m,0,0,n,"",visited);              return res;   }}
+1
jainmuskan5656 days ago
void solve(int i,int j,string move,vector<string>&res,vector<vector<int>> &m,vector<vector<int>>&visited,int n){
        if(i==n-1 && j==n-1){
            res.push_back(move);
            return;
        }
        if(i<0 || j<0 || i>n-1 ||j>n-1){
            return;
        }
        // base cases 
        if(visited[i][j]==1 || m[i][j]==0){
            return;
        }
        // down left right up (sorted order traversal)
        visited[i][j]=1;
        solve(i+1,j,move+"D",res,m,visited,n);
        solve(i,j-1,move+"L",res,m,visited,n);
        solve(i,j+1,move+"R",res,m,visited,n);
        solve(i-1,j,move+"U",res,m,visited,n);
        // backtracking step unvisit the position
        visited[i][j]=0;
    }
    vector<string> findPath(vector<vector<int>> &m, int n) {
        vector<vector<int>> visited(n,vector<int>(n,0));
        vector<string> res;
        if(m[0][0]==0 || m[n-1][n-1]==0){
            return res;
        }
        solve(0,0,"",res,m,visited,n);
        return res;
    }
0
harshmaheshwari1 week ago
simple recursion and backtracking
 vector<string> findPath(vector<vector<int>> &m, int n) {
        // Your code goes here
        vector<string> ans;
        findans(m,n,0,0,ans,"");
        if(ans.size()==0) return {"-1"};
        return ans;
        
    }
    void findans(vector<vector<int>> &m,int n, int i,int j, vector<string> &ans,string temp)
    {
        
        
        if(i>n-1 )
        return;
        if(j>n-1)
        return;
        if(j<0)
        return;
        if(i<0)
        return;
        
        if(m[i][j]==0)
        return ;
        
        if(i==n-1 && j==n-1)
        {
            ans.push_back(temp);
            return ;
        }
        
        if(m[i][j]==1)
        {
            m[i][j]=0;
        findans(m, n,  i+1,j ,ans, temp+"D");
         findans(m, n,  i,j+1 ,ans, temp+"R");
          findans(m, n,  i-1,j,ans, temp+"U");
           findans(m, n, i,j-1, ans, temp+"L");
             m[i][j] =1;
        }
           
    }
-1
shashank28931 week ago
#Python Working Code: Basic backtracking, if any neighbor is #1, move to the next neighbor and color the current neighbor #as -1. 

class Solution:
    def findPath(self, m, n):
        # code here
        # Edge case, the starting point is zero, not clear in question
        if m[0][0] == 0:
            return ['-1']
        
        self.ans, self.n = [], n
        
        self.dirs = {'R':[0,1], 
            'D': [1,0], 
            'L': [0, -1], 
            'U':[-1, 0]
    
        }
        
        self.helper(m, 0, 0, '')
        if self.ans:
            return self.ans
        else:
            return ['-1']
    
    def helper(self, m, x, y, path):
        if x == self.n - 1 and y == self.n - 1:
            self.ans.append(path)
            m[x][y] = 1
            return
    
        for d, val in self.dirs.items():
            x_next, y_next = x+val[0], y+val[1]
            if 0 <= x_next < self.n and 0<= y_next < self.n and m[x_next][y_next] == 1:
                m[x][y] = -1
                self.helper(m, x_next, y_next, path + d)
        
        if m[x][y] == -1:
            m[x][y] = 1
0
shubhamkavia19981 week ago
Can you tell the error
Thank You!
 
class Solution{
    public:
    vector<string>res;string str="";

    void dfs(vector<vector<int>> &m,int i,int j,int row,int col)
    {   
        if(i==(row-1) && j==(col-1)){ res.push_back(str); str=""; return;}
        if(valid(m,i,j,row,col))
        {   m[i][j]=2;
            dfs(m,i,j+1,row,col);str+='R';
            dfs(m,i,j-1,row,col);str+='L';
            dfs(m,i+1,j,row,col);str+='D';
            dfs(m,i-1,j,row,col);str+='U';
            m[i][j]=1;
            int p=str.size();
            str = str.substr(0,p-2);
        }
    }
    
    bool valid(vector<vector<int>> &m,int i,int j,int row,int col)
    {
        if(i<0||j<0||i>=row||j>=col)return false;
        else 
        {
            if(m[i][j]==1)
            return true;
            else if(m[i][j]==0 || m[i][j]==2)
            return false;
        }
    }
    vector<string> findPath(vector<vector<int>> &m, int n) {
        vector<string>gas;
        gas.push_back("-1");
        int row= m.size();int col=m[0].size();
        dfs(m,0,0,row,col);
        sort(res.begin(),res.end());
        if(res.empty()==0)
        return gas;
        return res;
     
    }
};
0
shubhamkavia1998
This comment was deleted.
+1
himanshu0719cse192 weeks ago
public static void helper(int[][] m,int n,String s,ArrayList<String>ans,int row,int col,boolean[][]visited)   {       //System.out.println(s);       if(row==n-1&&col==n-1)       {           ans.add(s);           return;       }       visited[row][col]=true;       int[]x={0,0,1,-1};       int[]y={1,-1,0,0};       char[]dir={'R','L','D','U'};       for(int i=0;i<4;i++)       {           int row1=row+x[i];           int col1=col+y[i];           boolean valid=row1>=0&&row1<n&&col1>=0&&col1<n&&!visited[row1][col1]&&m[row1][col1]!=0;           if(valid)           {               helper(m,n,s+dir[i],ans,row1,col1,visited);           }       }       visited[row][col]=false;   }   public static ArrayList<String> findPath(int[][] m, int n) {       ArrayList<String>ans=new ArrayList<>();       if(m[0][0]==0)       {           return ans;       }       boolean[][]visited=new boolean[n][n];       String s="";       helper(m,n,s,ans,0,0,visited);       return ans;   }
0
psadv
This comment was deleted.
+4
soniwalsushil242 weeks ago
JAVA MOST SIMPLE SOLUTION WITH COMMENTS.
 
class Solution {
static ArrayList<String> res = new ArrayList<>(); // Static arrayList.    static ArrayList<String> findPath(int[][] maze, int n) {        res.clear();        // If source or destination is a obstacle.        if (maze[0][0] == 0 || maze[n - 1][n - 1] == 0) {            return res;        }        printPath("", maze, 0, 0, n);        return res;    }    static void printPath(String ans, int[][] maze, int row, int col, int n) {        // Base Condition.        if (row == n - 1 && col == n - 1) {            res.add(ans);            return;        }        // Can't go.        if (maze[row][col] == 0) {            return;        }        // Consider This Cell In My Path.        maze[row][col] = 0;        // To Travel Down.        if (row < n - 1) {            printPath(ans + 'D', maze, row + 1, col, n);        }        // To Travel Right.        if (col < n - 1) {            printPath(ans + 'R', maze, row, col + 1, n);        }        // To Travel Up.        if (row > 0) {            printPath(ans + 'U', maze, row - 1, col, n);        }        // To Travel Left.        if (col > 0) {            printPath(ans + 'L', maze, row, col - 1, n);        }        // BackTrack:- Remove The Changes That We Were Made.        maze[row][col] = 1;    }}
+1
moaslam8263 weeks ago
c++ soln
void fun(vector<vector<int>>&m,vector<string> &ans,int row,int col,int max_row,int max_col,string str){

	if(row==max_row-1 && col==max_col-1){
     ans.push_back(str);
     return;
	}
    //upward validaton
    if(row-1>=0 &&m[row-1][col]!=0){
    	
    	string t=str;
    	t.push_back('U');
    	m[row][col]=0;
    	fun(m,ans,row-1,col,max_row,max_col,t);
    	m[row][col]=1;
    }
    //dowanward validation
    if(row+1<max_row && m[row+1][col]!=0){
    	string t=str;
    	t.push_back('D');
    	m[row][col]=0;
    	fun(m,ans,row+1,col,max_row,max_col,t);
    	m[row][col]=1;
    }
    //for left validation
    if(col-1>=0 && m[row][col-1]!=0){

    	string t=str;
    	t.push_back('L');
    	m[row][col]=0;
    	fun(m,ans,row,col-1,max_row,max_col,t);
    	m[row][col]=1;
    }
    //for right validation 
    if(col+1<max_col && m[row][col+1]!=0){
    	string t=str;
    	t.push_back('R');
    	m[row][col]=0;
    	fun(m,ans,row,col+1,max_row,max_col,t);
    	m[row][col]=1;
    }
}

    vector<string> findPath(vector<vector<int>> &m, int n) {
        if(m[n-1][n-1]==0) return {"-1"};
        if(m[0][0]==0) return {"-1"};
        vector<string> s;
        fun(m,s,0,0,n,n,"");
        if(s.size()==0) return {"-1"};
        return s;
    }
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
                    want to view the editorial?
 Login to access your submissions. 

Problem


Contest

Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.