@@ -73,7 +73,55 @@ To solve this problem, we use **backtracking**, which allows us to explore all p
7373
7474## Problem Solution
7575``` cpp
76+ class Solution {
77+ public:
78+ bool isSafe(int newX, int newY, vector<vector<bool >>& vis, vector<vector<int >>& arr, int n){
79+
80+ if((newX >= 0 && newX < n) && (newY >= 0 && newY < n) && vis[ newX] [ newY ] != 1 && arr [ newX] [ newY ] == 1) return true;
81+
82+ return false;
83+ }
84+
85+ void solve(int x, int y, vector<vector<int >>& arr, int n, vector<string >& ans, vector<vector<bool >>& vis, string path){
86+
87+ if(x == n-1 && y == n-1){
88+ ans.push_back(path);
89+ return;
90+ }
91+
92+ vis[ x] [ y ] = 1;
93+
94+ if(isSafe(x+1, y, vis, arr, n)){
95+ solve(x+1, y, arr, n, ans, vis, path + 'D');
96+ }
97+
98+ if(isSafe(x, y-1, vis, arr, n)){
99+ solve(x, y-1, arr, n, ans, vis, path + 'L');
76100
101+ }
102+
103+ if (isSafe(x, y+1 , vis, arr, n)){
104+ solve (x, y+1, arr, n, ans, vis, path + 'R');
105+ }
106+
107+ if(isSafe(x-1, y, vis, arr, n)){
108+ solve(x-1, y, arr, n, ans, vis, path + 'U');
109+ }
110+
111+ vis[ x] [ y ] = 0;
112+
113+ }
114+ vector<string > findPath(vector<vector<int >> &mat) {
115+ vector<string > ans;
116+ vector<vector<bool >> visited(mat.size(), vector<bool >(mat.size(), 0));
117+
118+ string path = "";
119+
120+ solve(0, 0, mat, mat.size(), ans, visited, path);
121+
122+ return ans;
123+ }
124+ };
77125```
78126
79127
0 commit comments