From 9d09b204c12ee004923b0221c2d556540891b47c Mon Sep 17 00:00:00 2001 From: Aviral Tandon <201951036@iiitvadodara.ac.in> Date: Sat, 2 Oct 2021 01:25:21 +0530 Subject: [PATCH] CPP Program for Rat in a Maze problem --- Rat_in_a_maze_Backtracking.cpp | 91 ++++++++++++++++++++++++++++++++++ 1 file changed, 91 insertions(+) create mode 100644 Rat_in_a_maze_Backtracking.cpp diff --git a/Rat_in_a_maze_Backtracking.cpp b/Rat_in_a_maze_Backtracking.cpp new file mode 100644 index 0000000..a465b99 --- /dev/null +++ b/Rat_in_a_maze_Backtracking.cpp @@ -0,0 +1,91 @@ + + +#include +using namespace std; + +// Rat in a Maze Problem (Backtracking) + +// 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. + +// 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. + +class Solution{ + public: + +void find(vector> &m,string s,int n,int i,int j,vector &ans) + { + if(i==n-1&&j==n-1) + { + ans.push_back(s); + return; + } + if(i>=0&&j>=0&&i findPath(vector> &m, int n) { + + vector ans; + string s; + if(m[0][0]==0||m[n-1][n-1]==0) + return ans; + + find(m,s,n,0,0,ans); + return ans; + + } +}; + + + + + + +int main() { + int t; + cin >> t; + while (t--) { + int n; + cin >> n; + vector> m(n, vector (n,0)); + for (int i = 0; i < n; i++) { + for (int j = 0; j < n; j++) { + cin >> m[i][j]; + } + } + Solution obj; + vector result = obj.findPath(m, n); + if (result.size() == 0) + cout << -1; + else + for (int i = 0; i < result.size(); i++) cout << result[i] << " "; + cout << endl; + } + return 0; +} \ No newline at end of file