Skip to content
Rain Hu's Workspace
Go back

[LeetCode] 433. Minimum Genetic Mutation

Rain Hu

433. Minimum Genetic Mutation


一、題目

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.

Example 1:

Example 2:

Example 3:

Constraints:


二、分析

三、解題

1. BFS

const string code = "ATCG";
int minMutation(string start, string end, vector<string>& bank) {
    unordered_set<string> set(bank.begin(), bank.end());
    if (!set.count(end)) return -1;
    queue<string> q;
    q.push(start);
    int cnt = 0;
    while (!q.empty()) {
        int sz = q.size();
        while (sz--) {
            string curr = q.front();
            q.pop();
            if (curr == end) return cnt;
            set.erase(curr);
            for (int i = 0; i < start.length(); i++) {
                string tmp = curr;
                for (char c : code){
                    tmp[i] = c;
                    if (set.count(tmp)) q.push(tmp);
                }
            }
        }
        cnt++;
    }
    return -1;
}

回目錄 Catalog


Share this post on:

Previous
[LeetCode] 2131. Longest Palindrome by Concatenating Two Letter Words
Next
[LeetCode] 1610. Maximum Number of Visible Points