-->

Sunday, December 18, 2016

127. Word Ladder

https://leetcode.com/problems/word-ladder/

Solution:
This question can be viewed as the most fundamental "breadth search first" (Breadth-first search - Wikipedia). The popular way to implement is using queue data structure to maintain each "level", as the search expands. For this question, a hash map can be used to store the "level" information.

Code: 
class Solution {
public:
    int ladderLength(string beginWord, string endWord, unordered_set<string>& wordList) {
        unordered_map<string, int> m;
        m[beginWord] = 1;
        queue<string> q;
        q.push(beginWord);
        while(!q.empty()){
            string s = q.front();
            q.pop();
            for(int i=0; i<s.size(); ++i){
                string s1 = s;
                for(int cr='a'; cr<='z'; ++cr){
                    s1[i] = cr;
                    if(s1 == endWord) return m[s] + 1;
                    if(wordList.find(s1) != wordList.end() && m.find(s1) == m.end()){
                        m[s1] = m[s] +1;
                        q.push(s1);
                    }
                }
            }
        }
        return 0;
    }
};

No comments :

Post a Comment