|
| 1 | +class Solution { |
| 2 | + public: |
| 3 | + bool isSafe(int newX, int newY, vector<vector<bool>>& vis, vector<vector<int>>& arr, int n){ |
| 4 | + |
| 5 | + if((newX >= 0 && newX < n) && (newY >= 0 && newY < n) && vis[newX][newY] != 1 && arr [newX][newY] == 1) return true; |
| 6 | + |
| 7 | + return false; |
| 8 | + } |
| 9 | + |
| 10 | + void solve(int x, int y, vector<vector<int>>& arr, int n, vector<string>& ans, vector<vector<bool>>& vis, string path){ |
| 11 | + |
| 12 | + if(x == n-1 && y == n-1){ |
| 13 | + ans.push_back(path); |
| 14 | + return; |
| 15 | + } |
| 16 | + |
| 17 | + vis[x][y] = 1; |
| 18 | + |
| 19 | + if(isSafe(x+1, y, vis, arr, n)){ |
| 20 | + solve(x+1, y, arr, n, ans, vis, path + 'D'); |
| 21 | + } |
| 22 | + |
| 23 | + if(isSafe(x, y-1, vis, arr, n)){ |
| 24 | + solve(x, y-1, arr, n, ans, vis, path + 'L'); |
| 25 | + |
| 26 | + } |
| 27 | + |
| 28 | + if(isSafe(x, y+1, vis, arr, n)){ |
| 29 | + solve(x, y+1, arr, n, ans, vis, path + 'R'); |
| 30 | + } |
| 31 | + |
| 32 | + if(isSafe(x-1, y, vis, arr, n)){ |
| 33 | + solve(x-1, y, arr, n, ans, vis, path + 'U'); |
| 34 | + } |
| 35 | + |
| 36 | + vis[x][y] = 0; |
| 37 | + |
| 38 | + } |
| 39 | + vector<string> findPath(vector<vector<int>> &mat) { |
| 40 | + vector<string> ans; |
| 41 | + vector<vector<bool>> visited(mat.size(), vector<bool>(mat.size(), 0)); |
| 42 | + |
| 43 | + string path = ""; |
| 44 | + |
| 45 | + solve(0, 0, mat, mat.size(), ans, visited, path); |
| 46 | + |
| 47 | + return ans; |
| 48 | + } |
| 49 | +}; |
0 commit comments