Problem Statement

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.

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.

Example 2:

Input:
N = 2
m[][] = {{1, 0},
         {1, 0}}
Output:
-1
Explanation:
No path exists and destination cell is
blocked.

Problem Link

Rat in a Maze Problem - I | Practice | GeeksforGeeks

Code (Using Backtracking)

class Solution{
    public:
    vector<string> findPath(vector<vector<int>> &maze, int n) {
        
      vector<string> res;
      string temp = "";
      
        
       if(maze[0][0]==0 or maze[n-1][n-1]==0)
       return res;
       
       vector<vector<bool>> visited(n,vector<bool>(n,false));    
        
       dfs(maze,0,0,n,res,temp,visited);
            
        
        return res;
    }
    void dfs(vector<vector<int>> &maze, int i, int j, int n,vector<string>& res,string &temp,vector<vector<bool>> &visited )
    {
        if(i<0 or j<0 or i>n-1 or j>n-1)
          return;
          
        if(visited[i][j] or !maze[i][j])
           return;
          
        if(i==n-1 and j==n-1)
        {
            res.push_back(temp);
            return;
        }
        
        visited[i][j] = true;
        
         if(i+1<=n-1 and !visited[i+1][j] and maze[i+1][j])
         {
            temp.push_back('D');
            dfs(maze,i+1,j,n,res,temp,visited);
            temp.pop_back();
         }
        
        if(j-1>=0 and !visited[i][j-1] and maze[i][j-1])
        {
            temp.push_back('L');
            dfs(maze,i,j-1,n,res,temp,visited);
            temp.pop_back();
        }
        
        if(j+1<=n-1 and !visited[i][j+1] and maze[i][j+1])
        {
            temp.push_back('R');
            dfs(maze,i,j+1,n,res,temp,visited);
            temp.pop_back();
        }
        
        
        if(i-1>=0 and !visited[i-1][j] and maze[i-1][j])
        {
            temp.push_back('U');
            dfs(maze,i-1,j,n,res,temp,visited);
            temp.pop_back();
        }
        
       
        visited[i][j] = false;
    }
};