|
| 1 | +# Unique Paths III |
| 2 | +[Question](https://leetcode.com/problems/unique-paths-iii/description/) |
| 3 | + |
| 4 | +# Solution: |
| 5 | +```cpp |
| 6 | +class Solution { |
| 7 | + |
| 8 | + int m, n, tWalk, ans; |
| 9 | + |
| 10 | + // m -> no. of rows |
| 11 | + // n -> no. of columns |
| 12 | + // tWalk -> total empty square to walk over i.e grid[i][j] == 0 |
| 13 | + // ans -> no. of ways to reach the ending square |
| 14 | + |
| 15 | + void DFS(vector<vector<int>> &grid, int i, int j) { |
| 16 | + |
| 17 | + // Condition to check the index are in range |
| 18 | + // & |
| 19 | + // there is no obstacle in the square |
| 20 | + if(i < 0 || i >= m || j < 0 || j >= n || grid[i][j] == -1) |
| 21 | + return; |
| 22 | + |
| 23 | + // Check Current Square is the ending Square |
| 24 | + if(grid[i][j] == 2) { |
| 25 | + // If there is no square left to walk over then |
| 26 | + // we have find a way to reach the ending square |
| 27 | + // so increment the ans and return else |
| 28 | + // return also because there are more square to |
| 29 | + // walk over before stepping in end square |
| 30 | + if(tWalk == -1) ans++; |
| 31 | + return; |
| 32 | + } |
| 33 | + |
| 34 | + // Mark current square has been walked so that |
| 35 | + // we don't walk over again |
| 36 | + grid[i][j] = -1; |
| 37 | + // Since we have walked one more square so |
| 38 | + // decrement total swaures to walk |
| 39 | + tWalk--; |
| 40 | + |
| 41 | + // Recursive call for Left Square |
| 42 | + DFS(grid, i, j-1); |
| 43 | + // Recursive call for Right Square |
| 44 | + DFS(grid, i, j+1); |
| 45 | + // Recursive call for Upward Square |
| 46 | + DFS(grid, i-1, j); |
| 47 | + // Recursive call for Downward Square |
| 48 | + DFS(grid, i+1, j); |
| 49 | + |
| 50 | + // Restore Total Walk |
| 51 | + tWalk++; |
| 52 | + // Restore current square identity |
| 53 | + grid[i][j] = 0; |
| 54 | + } |
| 55 | + |
| 56 | +public: |
| 57 | + |
| 58 | + int uniquePathsIII(vector<vector<int>>& grid) { |
| 59 | + |
| 60 | + m = grid.size(); |
| 61 | + n = grid[0].size(); |
| 62 | + ans = 0; |
| 63 | + tWalk = 0; |
| 64 | + |
| 65 | + int sx, sy; |
| 66 | + for(int i=0; i<m; i++) { |
| 67 | + for(int j=0; j<n; j++) { |
| 68 | + // Calaculating total square to walk over |
| 69 | + if(grid[i][j] == 0) tWalk++; |
| 70 | + // Storing the starting Square index |
| 71 | + if(grid[i][j] == 1) { |
| 72 | + sx = i; |
| 73 | + sy = j; |
| 74 | + } |
| 75 | + } |
| 76 | + } |
| 77 | + |
| 78 | + DFS(grid, sx, sy); |
| 79 | + |
| 80 | + return ans; |
| 81 | + } |
| 82 | + |
| 83 | +}; |
| 84 | +``` |
0 commit comments