Word Ladder
Given two words (start and end), and a dictionary, find the length of shortest transformation sequence from start to end, such that:
- Only one letter can be changed at a time
- 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代码实现:
- public int ladderLength(String start, String end, Set<String> dict) {
- Queue<String> canReach = new LinkedList<String>(); //一个Queue实现BFS
- Map<String,Integer> flag = new HashMap<String,Integer>(); //标记
- canReach.offer(start);
- flag.put(start,1);
- canReach.offer(null);
- int step = 1;
- while(canReach.size()!=0) { //LinkedList 方法只有size,无empty
- String top = canReach.poll();
- if(top==null) {
- step++;
- if(canReach.size()==0) break;
- else {
- canReach.offer(null);
- }
- continue;
- }
- for(int j=0;j<top.length();j++) {
- for(char i='a';i<='z';i++) {
- if(i==top.charAt(j)) continue;
- char [] tmpArray = top.toCharArray(); //java中修改一个String中一个字符比较麻烦
- tmpArray[j] = i;
- String tmp = new String(tmpArray);
- if(tmp.compareTo(end)==0) return step+1;
- if(dict.contains(tmp)) {
- if(!flag.containsKey(tmp)) {
- flag.put(tmp,1);
- canReach.offer(tmp);
- }
- }
- }
- }
- }
- return 0;
- }
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;
}

浙公网安备 33010602011771号