Advertisement
jayati

Rat in a Maze Problem - I

Oct 4th, 2023
1,357
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.15 KB | None | 0 0
  1. //{ Driver Code Starts
  2. // Initial template for C++
  3.  
  4. #include <bits/stdc++.h>
  5. using namespace std;
  6.  
  7.  
  8. // } Driver Code Ends
  9. // User function template for C++
  10.  
  11. class Solution{
  12.     public:
  13.     vector<string> ans;
  14.     bool isSafe(int newx,int newy,vector<vector<int>> &m,vector<vector<bool>> &vis,int n)
  15.     {
  16.         if((newx>=0 && newx<n) && (newy>=0 && newy<n) && vis[newx][newy]!=1 && m[newx][newy]==1)
  17.         {
  18.             return true;
  19.         }
  20.         return false;
  21.    
  22. }
  23.     void solve(int x,int y,vector<vector<int>> &m, int n,vector<vector<bool>> &vis,string path)
  24.     {
  25.         if(x==n-1 && y==n-1)
  26.         {
  27.             ans.push_back(path);
  28.             return;
  29.         }
  30.         vis[x][y]=1;
  31.         if(isSafe(x+1,y,m,vis,n))
  32.         {
  33.             solve(x+1,y,m,n,vis,path+'D');
  34.         }
  35.        
  36.         if(isSafe(x,y-1,m,vis,n))
  37.         {
  38.             solve(x,y-1,m,n,vis,path+'L');
  39.         }
  40.        
  41.         if(isSafe(x,y+1,m,vis,n))
  42.         {
  43.             solve(x,y+1,m,n,vis,path+'R');
  44.         }
  45.        
  46.         if(isSafe(x-1,y,m,vis,n))
  47.         {
  48.             solve(x-1,y,m,n,vis,path+'U');
  49.         }
  50.         vis[x][y]=0;
  51.     }
  52.    
  53.     vector<string> findPath(vector<vector<int>> &m, int n) {
  54.         //   vector<string> ans;
  55.           vector<vector<bool>> vis(n,vector<bool> (n,0));
  56.           string path="";
  57.           if(m[0][0]==0)
  58.           {
  59.               return ans;
  60.           }
  61.           solve(0,0,m,n,vis,path);
  62.           return ans;
  63.     }
  64. };
  65.  
  66.    
  67.  
  68.  
  69. //{ Driver Code Starts.
  70.  
  71. int main() {
  72.     int t;
  73.     cin >> t;
  74.     while (t--) {
  75.         int n;
  76.         cin >> n;
  77.         vector<vector<int>> m(n, vector<int> (n,0));
  78.         for (int i = 0; i < n; i++) {
  79.             for (int j = 0; j < n; j++) {
  80.                 cin >> m[i][j];
  81.             }
  82.         }
  83.         Solution obj;
  84.         vector<string> result = obj.findPath(m, n);
  85.         sort(result.begin(), result.end());
  86.         if (result.size() == 0)
  87.             cout << -1;
  88.         else
  89.             for (int i = 0; i < result.size(); i++) cout << result[i] << " ";
  90.         cout << endl;
  91.     }
  92.     return 0;
  93. }
  94. // } Driver Code Ends
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement