127. Word Ladder via java
阅读原文时间:2023年07月08日阅读:3

A classic BFS problem, that is, we use a Queue to store temporary solution and record the size of the current Queue.

For each node in this BFS tree, we try k times of transformation, k is the length of the word.

We record every word which already has been seen in case of a loop. Thus we need a HashSet.

public class Solution {
// use BFS to solve
// in every level of BFS searching,
// we find the word that replaced by one char and also in the dict without have seen before
// data structure: seen(HashSet), cur(Queue)
// assume that the wordList is not null, case insensitive, no duplicate, every word is non-empty
public int ladderLength(String beginWord, String endWord, List wordList) {
// Write your solution here
HashSet seen = new HashSet<>();
Queue cur = new LinkedList<>();
seen.add(beginWord);
cur.offer(beginWord);
int cnt = 1;
while(cur.size()>0){
cnt++;
int size = cur.size();
for(int i=0; i changed= getQualified(todo, j, wordList, seen);
for(String s: changed){
if(String.valueOf(s)==String.valueOf(endWord)){
return cnt;
}else{
cur.offer(s);
seen.add(s);
}
}
}
}
}
return 0;
}

private List getQualified(String from, int ignore, List wordList, HashSet seen){
List res = new ArrayList<>();
for(String s: wordList){
int flag = 0;
for(int i=0; i<from.length(); i++){
if(i!=ignore && from.charAt(i)!=s.charAt(i)){
flag=1;
}
}
if(flag==0 && !seen.contains(s)){
res.add(s);
}
}
return res;
}
}

手机扫一扫

移动阅读更方便

阿里云服务器
腾讯云服务器
七牛云服务器

你可能感兴趣的文章