In this Leetcode Minimum Genetic Mutation problem solution A gene string can be represented by an 8-character long string, with choices from 'A', 'C', 'G', and 'T'.

Suppose we need to investigate a mutation from a gene string start to a gene string end where one mutation is defined as one single character changed in the gene string.

For example, "AACCGGTT" --> "AACCGGTA" is one mutation.

There is also a gene bank bank that records all the valid gene mutations. A gene must be in bank to make it a valid gene string.

Given the two gene strings start and end and the gene bank bank, return the minimum number of mutations needed to mutate from start to end. If there is no such a mutation, return -1.

Note that the starting point is assumed to be valid, so it might not be included in the bank.

Leetcode Minimum Genetic Mutation problem solution


Problem solution in Python.

class Solution(object):
    def minMutation(self, start, end, bank):
        """
        :type start: str
        :type end: str
        :type bank: List[str]
        :rtype: int
        """
        if start == end:
            return 0
        if not(end in bank):
            return -1
        if sum([s1 != s2 for s1,s2 in zip(start, end)])==1:
            return 1
        
        new_start_min_mutation = []
        for mut in bank:
            if sum([s1 != s2 for s1,s2 in zip(start, mut)])==1:
                new_bank = [s for s in bank if s!= mut]
                min_temp = self.minMutation(mut,end,new_bank)
                if  min_temp == -1:
                    continue
                else:
                    new_start_min_mutation.append(1+min_temp)
                       
        if len(new_start_min_mutation) == 0:
            return -1
        else:
            return min(new_start_min_mutation)



Problem solution in Java.

class Solution {
    public int minMutation(String start, String end, String[] bank) {
        if(start == null && end == null) {
            return 0;
        }
        
        if(start == null || 
           end == null || 
           start.length() == 0 || 
           end.length() == 0 || 
           bank == null || 
           bank.length == 0 || start.length() != end.length()) {
            return -1;
        }
        
        Set<String> dictionary = new HashSet<>(Arrays.asList(bank));
        
        
        Queue<Pair> queue = new LinkedList<Pair>();
        queue.add(new Pair(start, 0));
        int result = Integer.MAX_VALUE;
        Set<String> visited = new HashSet<String>();
        visited.add(start);
        char[] container = {'A', 'C', 'G', 'T'};
        
        while(!queue.isEmpty()) {
            int size = queue.size();
            
            for(int i = 0; i < size; i++) {
                Pair current = queue.poll();
                String currentString = current.head;
                
                if(currentString.equalsIgnoreCase(end)) {
                    result = Math.min(result, current.steps);
                    continue;
                }
                
                for(int k = 0; k < currentString.length(); k++) {
                    for(int j = 0; j < 4; j++) {
                        String next = replacePosition(currentString, k, container[j]);
                        if(dictionary.contains(next)) {
                            if(!visited.contains(next)) {
                                visited.add(next);
                                queue.add(new Pair(next, current.steps + 1));
                            }
                        }
                    }
                }
            }
        }
        return result == Integer.MAX_VALUE ? -1 : result;
    }
    
    private String replacePosition(String input, int index, char next) {
        StringBuilder sb = new StringBuilder(input);
        sb.setCharAt(index, next);
        return sb.toString();
    }
}

class Pair {
    String head;
    int steps;
    
    public Pair(String head, int steps) {
        this.head = head;
        this.steps = steps;
    }
}


Problem solution in C++.

class Solution {
public:
    int minMutation(string start, string end, vector<string>& bank) {
        int n = bank.size();
        unordered_set<string> umap;
        for(int i=0;i<n;i++)
            umap.insert(bank[i]);
        queue<string> q;
        q.push(start);
        int ans = 0;
        vector<char> rs;
        rs.push_back('A');
        rs.push_back('C');
        rs.push_back('G');
        rs.push_back('T');
        unordered_set<string> us;
        while(!q.empty()){
            int count=0,size=q.size();
            while(count<size){
                string a = q.front();
                q.pop();
                if(a==end)
                    return ans;
                us.insert(a);
                for(int i=0;i<a.length();i++){
                    string tmp = a;
                    for(auto j : rs){
                        a[i]=j;
                        if(umap.find(a)!=umap.end() && us.find(a)==us.end()){
                            q.push(a);
                            us.insert(a);
                        }
                    }
                    a=tmp;
                }
                count++;
            }
            ans++;
        }
        return -1;
    }
};