【Lintcode】120.Word Ladder

题目:

Given two words (start and end), and a dictionary, find the length of shortest transformation sequence from start to end, such that:

  1. Only one letter can be changed at a time
  2. Each intermediate word must exist in the dictionary
 Example

Given:
start = "hit"
end = "cog"
dict = ["hot","dot","dog","lot","log"]

As one shortest transformation is "hit" -> "hot" -> "dot" -> "dog" -> "cog",
return its length 5.

题解:

  BFS

Solution 1 ()

class Solution {
public:
    int ladderLength(string start, string end, unordered_set<string> &dict) {
        if (start == end) {
            return 1;
        }
        int n = start.size();
        if (n < 1 || n != end.size()) {
            return 0;
        }
        
        queue<string> q;
        q.push(start);
        dict.erase(start);
        int length = 2;
        
        while (!q.empty()) {
            int size = q.size();
            for (int i = 0; i < size; ++i) {
                string cur = q.front();
                q.pop();
                for (int j = 0; j < n; ++j) {
                    char oldChar = cur[j];
                    for (char c = 'a'; c <= 'z'; ++c) {
                        if (c == oldChar) {
                            continue;
                        }
                        cur[j] = c;
                        if (cur == end) {
                            return length;
                        }
                        if (dict.find(cur) != dict.end()) {
                            q.push(cur);
                            dict.erase(cur);
                        }
                    }
                    cur[j] = oldChar;
                }
            }
            ++length;
        }
        return 0;
    }
};
原文地址:https://www.cnblogs.com/Atanisi/p/6875628.html