-
Notifications
You must be signed in to change notification settings - Fork 23
/
Copy pathLC0980.cpp
executable file
·49 lines (43 loc) · 1.09 KB
/
LC0980.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
/*
Problem Statement: https://leetcode.com/problems/unique-paths-iii/
Time: O(3ᵐ ˙ ⁿ)
Space: O(m • n)
Author: Mohammed Shoaib, github.com/Mohammed-Shoaib
*/
class Solution {
public:
int uniquePathsIII(vector<vector<int>>& grid) {
int m, n, paths, empty;
m = grid.size();
n = grid[0].size();
paths = empty = 0;
pair<int, int> start;
// traverse directions easily
vector<int> xdir = {-1, 0, 1, 0};
vector<int> ydir = {0, -1, 0, 1};
// helper function to count paths
function<void(int, int, int)> dfs = [&](int x, int y, int len) {
if (x < 0 || x == m || y < 0 || y == n || grid[x][y] == -1)
return;
else if (grid[x][y] == 2) {
paths += empty == len - 1;
return;
}
grid[x][y] = -1;
for (int k = 0; k < xdir.size(); k++) {
int new_x = x + xdir[k], new_y = y + ydir[k];
dfs(new_x, new_y, len + 1);
}
grid[x][y] = 0;
};
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++;
}
dfs(start.first, start.second, 0);
return paths;
}
};