Java實現 LeetCode 756 金字塔轉換矩陣(DFS)

756. 金字塔轉換矩陣

如今,咱們用一些方塊來堆砌一個金字塔。 每一個方塊用僅包含一個字母的字符串表示。java

使用三元組表示金字塔的堆砌規則以下:ide

對於三元組(A, B, C) ,「C」爲頂層方塊,方塊「A」、「B」分別做爲方塊「C」下一層的的左、右子塊。當且僅當(A, B, C)是被容許的三元組,咱們才能夠將其堆砌上。spa

初始時,給定金字塔的基層 bottom,用一個字符串表示。一個容許的三元組列表 allowed,每一個三元組用一個長度爲 3 的字符串表示。code

若是能夠由基層一直堆到塔尖就返回 true,不然返回 false。字符串

示例 1:

輸入: bottom = "BCD", allowed = ["BCG", "CDE", "GEA", "FFF"]
輸出: true
解析:
能夠堆砌成這樣的金字塔:
    A
   / \
  G   E
 / \ / \
B   C   D

由於符合('B', 'C', 'G'), ('C', 'D', 'E')('G', 'E', 'A') 三種規則。
示例 2:

輸入: bottom = "AABA", allowed = ["AAA", "AAB", "ABA", "ABB", "BAC"]
輸出: false
解析:
沒法一直堆到塔尖。
注意, 容許存在像 (A, B, C)(A, B, D) 這樣的三元組,其中 C != D。

注意:get

bottom 的長度範圍在 [2, 8]。
allowed 的長度範圍在[0, 200]。
方塊的標記字母範圍爲{‘A’, ‘B’, ‘C’, ‘D’, ‘E’, ‘F’, ‘G’}。string

class Solution {
   public boolean pyramidTransition(String bottom, List<String> allowed) {
        if(allowed==null||allowed.size()==0)return false;
        HashMap<String,List<String>> dir=new HashMap<>(16);
        for(String str:allowed)
        {
            String head=str.substring(0,2);
            String ch=str.substring(2,3);
            if(dir.containsKey(head))
            {
                dir.get(head).add(ch);
            }
            else
            {
                List<String>p=new ArrayList<>();
                p.add(ch);
                dir.put(head,p);
            }
        }
        return(dfs(bottom, "",dir));
    }
    static boolean dfs(String last,String now,HashMap<String,List<String>> dir){
        if(last.length()==2&&now.length()==1) {
            return true;
        }
        if(now.length()==last.length()-1){
            return dfs(now,"",dir);
        }
        int start=now.length();int end=now.length()+2;
        List<String> p=dir.get(last.substring(start, end));
        if(p==null) return false;
        for (int i = 0; i < (p).size(); i++) {
            if(dfs(last,now+p.get(i),dir)) {
                return true;
            }
        }
        return false;
    }
}
相關文章
相關標籤/搜索