题目:Word Ladder
难度:medium
问题描述:
Given two words (beginWord and endWord), and a dictionary's word list, find the length of shortest transformation sequence from beginWord to endWord, such that:
- Only one letter can be changed at a time
- Each intermediate word must exist in the word list
For example,
Given:
beginWord = "hit"
endWord = "cog"
wordList = ["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即可。在两个String判断是否相邻时要注意,对wordlist,不要用枚举,因为wordlist的量可能非常非常大,会超时。要对另一个String进行修改后对wordList进行contains判定才能不超时、
代码如下:
public class Solution {
public int ladderLength(String beginWord, String endWord, Set<String> wordList) {
wordList.add(endWord);
Queue<String> queue=new LinkedList<String>();
queue.add(beginWord);
int level=0;
while(!queue.isEmpty()){
int len=queue.size();
for(int i=0;i<len;i++){
String temp=queue.poll();
if(temp.equals(endWord)){
return level+1;
}
for(int j=0;j<temp.length();j++){
char[] cs=temp.toCharArray();
for(char c='a';c<'z';c++){
cs[j]=c;
String check=new String(cs);
if(!check.equals(temp)&&wordList.contains(check)){
queue.add(check);
wordList.remove(check);
}
}
}
}
level++;
}
return 0;
}
}
另外,我也造轮子解了一次题~并且犯了上面说的错误,妥妥的超时、
轮子代码如下:
public class node{
String Value;
HashSet<node> nodelist;
public node(String v){
nodelist=new HashSet<>();
Value=v;
}
public void add(node x){
nodelist.add(x);
}
}
public class Graph{
public ArrayList<node> graphSet;
public Graph(HashSet<node> nodset){
graphSet=new ArrayList<>(nodset);
}
public int route(String s1,String s2){
node n1,n2;
n1=new node("");
n2=new node("");
for(node w:graphSet){
if(w.Value.equals(s1)){
n1=w;
}
if(w.Value.equals(s2)){
n2=w;
}
}
Queue<node> queue=new LinkedList<>();
queue.add(n1);
int count=0;
while(queue.size()>0){
int len=queue.size();
for(int i=0;i<len;i++){
node temp=queue.poll();
if(isnext(temp.Value,n2.Value)){
return count+2;
}
for(node w:graphSet){
if(isnext(temp.Value,w.Value)){
queue.add(w);
}
}
}
count++;
}
return 0;
}
}
public Graph getGraph(String beginWord, String endWord, Set<String> wordList){
HashSet<node> nodset=new HashSet<node>();
for(String w:wordList){
node temp=new node(w);
nodset.add(temp);
}
nodset.add(new node(beginWord));
nodset.add(new node(endWord));
for(node w:nodset){
for(node x:nodset){
if(isnext(w.Value,x.Value)){
if(!w.nodelist.contains(x)){
w.nodelist.add(x);
}
if(!x.nodelist.contains(w)){
x.nodelist.add(w);
}
}
}
}
return new Graph(nodset);
}
public static boolean isnext(String s1,String s2){
if(s1.length()!=s2.length()) return false;
int count=0;
for(int i=0;i<s1.length();i++){
if(s1.charAt(i)!=s2.charAt(i)){
count++;
}
}
return count==1;
}