leetcode 84: Word Ladder

来源:互联网 发布:玻璃优化排版软件下载 编辑:程序博客网 时间:2024/04/27 02:28
Word LadderFeb 11

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.


first try: dfs can only pass small test case.  2nd try: bfs works. since the bfs is not using recursion. DFS will TLE in large tests, because it exhaust all possibilities.
BFS avoids this by finding only the shortest path.

class Solution {public:    int ladderLength(string start, string end, unordered_set<string> &dict) {        // Start typing your C/C++ solution below        // DO NOT write int main() function        min_value = INT_MAX;        unordered_set<string> unique;                ladderRec(start, end, dict, unique, 0);        return min_value==INT_MAX ? 0 : min_value;    }    private:    int min_value;        void ladderRec(const string & start, const string & end, unordered_set<string> &dict, unordered_set<string> &unique, int level) {        if( start==end) {            min_value = min(min_value, level+1);            return;        }                if(unique.size()==dict.size()) {            return;        }                if(level>start.length()) return;                for(int i=0; i<start.size(); i++) {            string temp = start;            for(char c='a'; c<='z'; c++) {                temp[i] = c;                if( dict.find(temp)!=dict.end() && unique.find(temp)==unique.end() ) {                    unique.insert(temp);                    ladderRec(temp, end, dict, unique, level+1);                      unique.erase(temp);                }            }        }    }};


class Solution {public:    int ladderLength(string start, string end, unordered_set<string> &dict) {        // Start typing your C/C++ solution below        // DO NOT write int main() function        if(start.size()!=end.size()) return 0;        if(start == end) return 2;                int min_value = 0;        unordered_set<string> unique;        unique.insert(start);                queue<string> que;        que.push(start);        int q1=1;        int q2=0;                while(q1>0) {            string s = que.front();            que.pop();            --q1;                        for(int i=0; i<s.size(); i++) {                string temp = s;                for(char c='a'; c<='z'; c++) {                    temp[i] = c;                    if(dict.find(temp)!=dict.end() && unique.find(temp)==dict.end()) {                        if(temp == end) {                            return min_value+2;                         } else {                            unique.insert(temp);                            que.push(temp);                            ++q2;                        }                    }                }            }                        if(q1==0) {                q1 = q2;                q2 = 0;                ++min_value;            }        }        return 0;    }};



public class Solution {    public int ladderLength(String start, String end, HashSet<String> dict) {        // Start typing your Java solution below        // DO NOT write main() function                int sz1 = start.length();        int sz2 = start.length();        int path = 0;        if(sz1 != sz2) return 0;        if(start.equals(end) ) return 2;                Queue<String> queue = new LinkedList<String>();                queue.offer( start );                HashSet<String> hitted = new HashSet<String>();        hitted.add(start);                int l1 = 1;        int l2 = 0;        //BFS        while( !queue.isEmpty() ) {            String s = queue.poll();            l1--;            HashSet<String> strs = nextStr(s,dict, hitted);            l2 += strs.size();                              for(String str : strs ) {                if( str.equals( end ) ) {                    return path+2;                } else {                    queue.offer( str );                }            }                        if(l1==0) {                ++path;                l1=l2;                l2=0;            }        }        return 0;    }        private HashSet<String> nextStr(String s, HashSet<String> dict, HashSet<String> hitted) {        HashSet<String> strs = new HashSet<String>();                for(int i=0; i<s.length(); i++) {            StringBuilder sb = new StringBuilder(s);            for(char c='a'; c<='z'; c++) {                 sb.setCharAt(i,c);                 String t = sb.toString();                 if( dict.contains( t ) && !hitted.contains( t) ) {                    hitted.add( t);                    strs.add( t );                 }            }        }                return strs;    } }


 


原创粉丝点击