LeetCode OJ - 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

For 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.

Note:

  • Return 0 if there is no such transformation sequence.
  • All words have the same length.
  • All words contain only lowercase alphabetic characters.

分析:BFS,樹的每一層都代表可達的字符串。當在某一層找到end時,路徑長度一定是最小的。

class Solution {
public:
    int ladderLength(string start, string end, unordered_set<string> &dict) {
        int ans = 2;
        dict.erase(start);
        dict.erase(end);
     
        queue<string> que;
        que.push(start);
        queue<string> next;

        while (!que.empty())
        {
            string s = que.front();
            que.pop();

            //層次遍歷
            for(int i = 0; i < s.size(); i++) {
                char tmp = s[i];
                //測試是否可達end
                for(char ch = 'a'; ch <= 'z'; ch++) {
                    s[i] = ch;
                    if(s == end) return ans;
                    if(dict.count(s)) {
                        dict.erase(s);
                        next.push(s);
                    }
                }
                
                s[i] = tmp;
            }
            
            //進入下一層
            if(que.empty()) {
                ans++;
                swap(que, next);
            }
        }
        return 0;
    }
};

        當然que和next可以做下優化,不需要交換操作,使用queue<int> que[2]來操作。





發佈了210 篇原創文章 · 獲贊 3 · 訪問量 13萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章