public boolean pyramidTransition(String bottom, List<String> allowed) {
Map<String, Set<Character>> map = new HashMap<>();
for (String s : allowed) {
String key = s.substring(0, 2);
if (!map.containsKey(key)) {
map.put(key, new HashSet<>());
map.get(key).add(s.charAt(2));
return canReachTop(bottom, "", map);
public boolean canReachTop(String curLevel, String lastLevel, Map<String, Set<Character>> map) {
if (curLevel.length() == 2 && lastLevel.length() == 1) {
if (lastLevel.length() == curLevel.length() - 1) {
return canReachTop(lastLevel, "", map);
int index = lastLevel.length();
String key = curLevel.substring(index, index + 2);
if (map.containsKey(key)) {
for (char c : map.get(key)) {
if (canReachTop(curLevel, lastLevel + c, map)) {