We are stacking blocks to form a pyramid. Each block has a color which is a one letter string, like `'Z'`.
For every block of color `C` we place not in the bottom row, we are placing it on top of a left block of color `A` and right block of color `B`. We are allowed to place the block there only if `(A, B, C)` is an allowed triple.
We start with a bottom row of bottom
, represented as a single string. We also start with a list of allowed triples allowed
. Each allowed triple is represented as a string of length 3.
Return true if we can build the pyramid all the way to the top, otherwise false.
Example 1:
Input: bottom = "XYZ", allowed = ["XYD", "YZE", "DEA", "FFF"] Output: true Explanation: We can stack the pyramid like this: A / \ D E / \ / \ X Y Z This works because ('X', 'Y', 'D'), ('Y', 'Z', 'E'), and ('D', 'E', 'A') are allowed triples.
Example 2:
Input: bottom = "XXYX", allowed = ["XXX", "XXY", "XYX", "XYY", "YXZ"] Output: false Explanation: We can't stack the pyramid to the top. Note that there could be allowed triples (A, B, C) and (A, B, D) with C != D.
Note:
bottom
will be a string with length in range[2, 8]
.allowed
will have length in range[0, 200]
.- Letters in all strings will be chosen from the set
{'A', 'B', 'C', 'D', 'E', 'F', 'G'}
.
判断,从字符串bottom开始,利用allowed中的三角关系,能否堆成一个金字塔状的图形。
DFS求解,本例中,可以相判断一层的情况,什么意思?可以判断bottom中的所有字符,相邻的两个字符能否符合allowed数组里面的要求。
判断一层的情况后,再向上层,利用判断一层的方法,层层向上判断。
这里面比较麻烦的一个地方是,如何进行分层判断,本例中,在字符串最末尾加入了一个' '空格字符,用于标记层与层之间的间隔,如下所示:
class Solution {
public boolean pyramidTransition(String bottom, List<String> allowed) {
Map<String, List<Character>> map = new HashMap<>();
Set<String> set = new HashSet<>();
for (String s : allowed){
if (!set.contains(s)){
set.add(s);
String str = s.substring(0, 2);
List<Character> list = map.getOrDefault(str, new ArrayList<Character>());
list.add(s.charAt(2));
map.put(str, list);
}
}
return dfs(bottom + ' ', map);
}
public boolean dfs(String bottom, Map<String, List<Character>> map){
if (bottom.length() == 1){
return true;
}
String s = bottom.substring(0, 2);
if (bottom.charAt(1) == ' '){
bottom = bottom.substring(2, bottom.length()) + ' ';
return dfs(bottom, map);
}
if (map.containsKey(s)){
for (char c : map.get(s)){
if (dfs(bottom.substring(1, bottom.length()) + c, map)){
return true;
}
}
}
return false;
}
}