-
Notifications
You must be signed in to change notification settings - Fork 19
Expand file tree
/
Copy pathsolution.java
More file actions
39 lines (34 loc) · 1.19 KB
/
solution.java
File metadata and controls
39 lines (34 loc) · 1.19 KB
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 {
Map<String, List<Character>> rules = new HashMap<>();
Set<String> bad = new HashSet<>();
public boolean pyramidTransition(String bottom, List<String> allowed) {
for (String s : allowed) {
rules.computeIfAbsent(s.substring(0, 2), k -> new ArrayList<>())
.add(s.charAt(2));
}
return dfs(bottom, 0, new StringBuilder());
}
private boolean dfs(String row, int idx, StringBuilder next) {
if (row.length() == 1)
return true;
if (idx == row.length() - 1) {
String nextRow = next.toString();
if (bad.contains(nextRow))
return false;
boolean ok = dfs(nextRow, 0, new StringBuilder());
if (!ok)
bad.add(nextRow);
return ok;
}
String key = row.substring(idx, idx + 2);
if (!rules.containsKey(key))
return false;
for (char c : rules.get(key)) {
next.append(c);
if (dfs(row, idx + 1, next))
return true;
next.deleteCharAt(next.length() - 1);
}
return false;
}
}