Skip to content

Create 11_uniquePathsiii.cpp #172

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
63 changes: 63 additions & 0 deletions 11 November Leetcode Challenge 2021/11_uniquePathsiii.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
static int X[4] = {-1, 0, 1, 0};
static int Y[4] = {0, -1, 0, 1};

class Solution {
public:

int countPaths(vector<vector<int>>& grid, int x, int y, int empty, const int& m, const int& n) {

/*
for(int i=0; i<m; i++) {
for(int j=0; j<n; j++) {
cout << grid[i][j] << " ";
}
cout << endl;
}
cout << x << " : " << y << " -> " << empty << endl << endl;
*/

// If we reach end cell and
// All empty cells are visited, then return 1
// Else return 0
if(grid[x][y] == 2) {
return (empty == 0);
}

int count = 0; // Count of possible paths from current cell {x,y}
grid[x][y] = -1; // Visit

// Check for all valid directions
for(int k=0; k<4; k++) {
// Possible adjacent coordinates
int i = x + X[k];
int j = y + Y[k];

// Valid Moves
if(i>=0 && j>=0 && i<m && j<n && grid[i][j] != -1) {
count += countPaths(grid, i, j, empty-1, m, n); // Add count of possible paths
}
}

// Backtrack
grid[x][y] = 0; // Unvisit

return count;
}

int uniquePathsIII(vector<vector<int>>& grid) {

int m = grid.size(), n = grid[0].size(), empty = 1;

pair<int, int> start;

for(int i=0; i<m; i++) {
for(int j=0; j<n; j++) {
if(grid[i][j] == 1) start = {i, j};
else if(grid[i][j] == 0) empty++; // Count of empty cells
}
}

// Explore grid from start cell
return countPaths(grid, start.first, start.second, empty, m, n);
}
};