From 44f17197a2d168b4e64b61ad3be9cdeb4fc554d4 Mon Sep 17 00:00:00 2001 From: ApurvGangavane Date: Sun, 24 Oct 2021 00:18:50 +0530 Subject: [PATCH] Added Search in a Maze (Greedy) CPP solution --- C++/Search_in_a_Maze.cpp | 77 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 77 insertions(+) create mode 100644 C++/Search_in_a_Maze.cpp diff --git a/C++/Search_in_a_Maze.cpp b/C++/Search_in_a_Maze.cpp new file mode 100644 index 0000000..7a97a78 --- /dev/null +++ b/C++/Search_in_a_Maze.cpp @@ -0,0 +1,77 @@ +/* + * 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. + */ + +#include +using namespace std; + +class Solution{ +public: + void dfs(vector> &g, int i, int j, int n, vector &result, string path){ + // Here i is row and j is column + if(i < 0 || j < 0 || i >= n || j >= n || g[i][j] != 1 ){ + return; + } + + if( (i== n-1) && (j == n-1)){ + result.push_back(path); + return; + } + + g[i][j] = -1; + dfs(g, i+1, j, n, result, path+"D"); + dfs(g, i, j+1, n, result, path+"R"); + dfs(g, i-1, j, n, result, path+"U"); + dfs(g, i-1, j-1, n, result, path+"L"); + g[i][j] = 1; + + } + + vector Search_Maze(vector> &graph, int n){ + vector result; + string ans = ""; + dfs(graph, 0 , 0, n, result, ans); + sort(result.begin(), result.end()); + return result; + } +}; + +int main() { + Solution obj; + + int size; + cout<<"Enter size of N*N graph: "; + cin>>size; + cout<> vec(size, (vector (size, -1))); + + cout<<"Enter elements of graph/Matrix: "<>vec[i][j]; + } + } + + vector res = obj.Search_Maze(vec, size); + + cout<<"Answer is: "; + if(res.size() == 0){ + cout<< -1<