方法一:两个队列遍历
class Solution {
public int ladderLength(String beginWord, String endWord, List<String> wordList) {
Queue<String> queue1 = new LinkedList<>();
Queue<String> queue2 = new LinkedList<>();
HashSet<String> set = new HashSet<>(wordList);
int step = 1;
queue1.offer(beginWord);
while(!queue1.isEmpty()){
String pos = queue1.poll();
if(pos.equals(endWord)){
return step;
}
List<String> neighbor = getNeighbor(pos);
for(String str : neighbor){
if(set.contains(str)){
queue2.offer(str);
set.remove(str);
}
}
if(queue1.isEmpty()){
queue1 = queue2;
queue2 = new LinkedList<>();
step++;
}
}
return 0;
}
private List<String> getNeighbor(String str){
char[] strChar = str.toCharArray();
List<String> result = new LinkedList<>();
for(int i = 0;i < strChar.length;i++){
char old = strChar[i];
for(char c = 'a';c <= 'z';c++){
if(c != old){
strChar[i] = c;
result.add(new String(strChar));
}
}
strChar[i] = old;
}
return result;
}
}
方法二:双向广度优先搜索
class Solution {
public int ladderLength(String beginWord, String endWord, List<String> wordList) {
Set<String> notVisited = new HashSet<>(wordList);
if(!notVisited.contains(endWord)){
return 0;
}
Set<String> set1 = new HashSet<>();
set1.add(beginWord);
notVisited.remove(beginWord);
Set<String> set2 = new HashSet<>();
set2.add(endWord);
notVisited.remove(endWord);
int step = 2;
while(set1.size() != 0 && set2.size() != 0){
if(set1.size() > set2.size()){
Set<String> temp = new HashSet<>();
temp = set1;
set1 = set2;
set2 = temp;
}
Set<String> set3 = new HashSet<>();
for(String str : set1){
List<String> neighbor = getNeighbor(str);
for(String s : neighbor){
if(set2.contains(s)){
return step;
}
if(notVisited.contains(s)){
set3.add(s);
notVisited.remove(s);
}
}
}
set1 = set3;
step++;
}
return 0;
}
private List<String> getNeighbor(String str){
char[] strChar = str.toCharArray();
List<String> result = new LinkedList<>();
for(int i = 0;i < strChar.length;i++){
char old = strChar[i];
for(char c = 'a';c <= 'z';c++){
if(c != old){
strChar[i] = c;
result.add(new String(strChar));
}
}
strChar[i] = old;
}
return result;
}
}
|