leetcode 84: Word Ladder

Word Ladder Feb 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;
    } 
}


 


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值