LeetCode 五月打卡-day07

Posted 王六六的IT日常

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode 五月打卡-day07相关的知识,希望对你有一定的参考价值。

433. 最小基因变化

图论搜索 : 「BFS」&「双向 BFS」&「A* 算法」&「建图 + DFS」

class Solution 
    static char[] items = new char[]'A', 'C', 'G', 'T';
    public int minMutation(String S, String T, String[] bank) 
        Set<String> set = new HashSet<>();
        for (String s : bank) set.add(s);
        Deque<String> d = new ArrayDeque<>();
        Map<String, Integer> map = new HashMap<>();
        d.addLast(S);
        map.put(S, 0);
        while (!d.isEmpty()) 
            int size = d.size();
            while (size-- > 0) 
                String s = d.pollFirst();
                char[] cs = s.toCharArray();
                int step = map.get(s);
                for (int i = 0; i < 8; i++) 
                    for (char c : items) 
                        if (cs[i] == c) continue;
                        char[] clone = cs.clone();
                        clone[i] = c;
                        String sub = String.valueOf(clone);
                        if (!set.contains(sub)) continue;
                        if (map.containsKey(sub)) continue;
                        if (sub.equals(T)) return step + 1;
                        map.put(sub, step + 1);
                        d.addLast(sub);
                    
                
            
        
        return -1;
    

以上是关于LeetCode 五月打卡-day07的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode 五月打卡-day01

LeetCode 五月打卡-day19

LeetCode 五月打卡-day20

LeetCode 五月打卡-day08

LeetCode 五月打卡-day13

LeetCode 五月打卡-day06