-
-
Notifications
You must be signed in to change notification settings - Fork 8.8k
/
Copy pathSolution.cpp
39 lines (37 loc) · 1002 Bytes
/
Solution.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
class Solution {
public:
int f[7][7];
unordered_map<string, bool> dp;
bool pyramidTransition(string bottom, vector<string>& allowed) {
memset(f, 0, sizeof f);
for (auto& s : allowed) {
int a = s[0] - 'A', b = s[1] - 'A';
f[a][b] |= 1 << (s[2] - 'A');
}
return dfs(bottom, "");
}
bool dfs(string& s, string t) {
if (s.size() == 1) {
return true;
}
if (t.size() + 1 == s.size()) {
return dfs(t, "");
}
string k = s + "." + t;
if (dp.count(k)) {
return dp[k];
}
int a = s[t.size()] - 'A', b = s[t.size() + 1] - 'A';
int cs = f[a][b];
for (int i = 0; i < 7; ++i) {
if ((cs >> i) & 1) {
if (dfs(s, t + (char) (i + 'A'))) {
dp[k] = true;
return true;
}
}
}
dp[k] = false;
return false;
}
};