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的思想进行求解,每一步表示可以搜索到的集合;然后再这个集合的基础上再进行搜索,知道找到目标

注意事项: 避免出现循环,所以需要将已经搜索到的目标进行标记,或者从搜索集合中去掉(两种方法都可以)

java代码实现:

  1. public int ladderLength(String start, String end, Set<String> dict) {
  2. Queue<String> canReach = new LinkedList<String>();  //一个Queue实现BFS
  3. Map<String,Integer> flag = new HashMap<String,Integer>();  //标记
  4. canReach.offer(start);
  5. flag.put(start,1);
  6. canReach.offer(null);
  7. int step = 1;
  8. while(canReach.size()!=0) {  //LinkedList 方法只有size,无empty
  9. String top = canReach.poll();
  10. if(top==null) {
  11. step++;
  12. if(canReach.size()==0) break;
  13. else {
  14. canReach.offer(null);
  15. }
  16. continue;
  17. }
  18. for(int j=0;j<top.length();j++) {
  19. for(char i='a';i<='z';i++) {
  20. if(i==top.charAt(j)) continue;
  21. char [] tmpArray = top.toCharArray();  //java中修改一个String中一个字符比较麻烦
  22. tmpArray[j] = i;
  23. String tmp = new String(tmpArray);
  24. if(tmp.compareTo(end)==0) return step+1;
  25. if(dict.contains(tmp)) {
  26. if(!flag.containsKey(tmp)) {
  27. flag.put(tmp,1);
  28. canReach.offer(tmp);
  29. }
  30. }
  31. }
  32. }
  33. }
  34. return 0;
  35. }

C++代码:

int ladderLength(string start, string end, unordered_set<string> &dict) {
if(dict.empty() && start!=end) return 0;
if(dict.empty() && start==end) return 1;
int dsz = dict.size();
string cur;
cur.clear();
int len=1;
queue<string> queToPop,queToPush;  //两个queue来实现层次遍历
queToPop.push(start);
while(dict.size()>0 && !queToPop.empty()) {
while(!queToPop.empty()) {
string str(queToPop.front());
queToPop.pop();
for(int i=0;i<str.size();i++) {
for(char j='a';j<='z';j++) {
if(j==str[i])
continue;
char temp=str[i];
str[i]=j;
if(str==end)
return len+1;
if(dict.count(str)>0) {
queToPush.push(str);
dict.erase(str);
}
str[i]=temp;
}
}
}
swap(queToPush,queToPop);
len++;
}
return 0;
}

posted @ 2014-07-27 10:33  purejade  阅读(101)  评论(0)    收藏  举报