127. Word Ladder
# hard
这道题不仅代码不好写,还很容易超时,前后尝试了3种方法:
class Solution {
int ladder = Integer.MAX_VALUE;
List<String> path = new ArrayList<String>();
public int ladderLength(String beginWord, String endWord, List<String> wordList) {
dfs(beginWord, endWord, wordList, 0);
if(ladder < Integer.MAX_VALUE) return ladder;
else return 0;
}
void dfs(String beginWord, String endWord, List<String> wordList, int count){
if(beginWord.compareTo(endWord) == 0){
if(count+1 < ladder) {
ladder = count+1;
for(int x = 0; x < path.size(); x++)
System.out.print(";"+ path.get(x));
}
System.out.println();
return;
}
for(int i = 0; i < beginWord.length(); i ++){
int j = 0;
while(j < wordList.size()){
StringBuilder temp = new StringBuilder();
for(int x = 0; x < beginWord.length(); x ++){
temp.append(beginWord.charAt(x));
}
j = change(temp,wordList,i,j); // i is the character in word will be changed, j is the start searching index of wordList
if(j == 0)
break;
String begin = new String(temp);
// System.out.println("begin="+ begin);
path.add(begin);
dfs(begin, endWord, wordList, count+1);
path.remove(path.size()-1);
}
}
}
int change(StringBuilder temp, List<String> wordList, int i,int j){
// System.out.println("enter change temp = "+ temp);
char ch = temp.charAt(i);
String alph = new String("abcdefghijklmnopqrstuvwxyz");
for(int x = 0; x < 26; x++){
if(ch == alph.charAt(x)) {
continue;
}
temp.setCharAt(i, alph.charAt(x));
if(wordList.contains(new String(temp)) && !path.contains(new String(temp)) && wordList.indexOf(new String(temp)) >= j){
// System.out.println("new temp="+temp);
return wordList.indexOf(new String(temp))+1;
}
}
// for(int x = j; x < wordList.size(); x ++){
// if(path.contains(wordList.get(x))) continue;
// boolean flag1 = true, flag2 = true;
// for(int y = 0; y < temp.length(); y ++){
// if(y == i && temp.charAt(i) == wordList.get(x).charAt(y)) {
// flag1 = false;
// break;
// }
// if(y != i && temp.charAt(y) != wordList.get(x).charAt(y)){
// flag2 = false;
// break;
// }
// }
// //System.out.println("worldList=" + wordList.get(x));
// if(flag1 && flag2){
// // System.out.println("enter true");
// temp.setCharAt(i, wordList.get(x).charAt(i));
// // System.out.println("intend change word to=" + wordList.get(x));
// // System.out.println("temp =" + temp);
// return x+1;
// }
// }
return 0;
}
}Last updated