思路
题来自:https://leetcode.com/problems/word-ladder/description/
- 经过分析:该单词转换的问题可以转变成一个图的问题,在图中寻找最小路径的问题。
- 解题步骤:
- 定义一个函数用来判断哪些字符串间可以相互转换 (canTransform方法),只有一个字符不相同。
- 将题转化成一个图数据结构(临接表)
- 使用bfs来进行搜索,寻找到出发点到目的地的最小路径
public class WordLadder {
public static void main(String[] args){
System.out.println(ladderLength("hit","cog",new ArrayList<>(Arrays.asList("hot","dot","dog","lot","log","cog"))));
}
public static int ladderLength(String beginWord, String endWord, List<String> wordList) {
Map<String,List<String>> graph=constructGraph(wordList,beginWord,endWord);
LinkedList<WordAndStep> stack=new LinkedList<>();
HashSet<String> visitedList=new HashSet<>();
stack.offer(new WordAndStep(beginWord,1));
visitedList.add(beginWord);
while (!stack.isEmpty()){
WordAndStep wordAndStep=stack.poll();
if (wordAndStep.getWord().equals(endWord)) {
return wordAndStep.getStep();
}else{
int step=wordAndStep.getStep();
List<String> wordList4Word=graph.get(wordAndStep.getWord());
for (String word:wordList4Word){
if (!visitedList.contains(word)) {
stack.offer(new WordAndStep(word,step+1));
visitedList.add(word);
}
}
}
}
return 0;
}
private static Map<String,List<String>> constructGraph(List<String> wordList, String beginWord, String endWord){
wordList.add(beginWord);
Map<String,List<String>> map=new HashMap<>();
for (int i=0;i<wordList.size();i++){
map.put(wordList.get(i),new ArrayList<>());
}
for (int i=0;i<wordList.size();i++){
for (int j=i;j<wordList.size();j++){
if (canTransform(wordList.get(i),wordList.get(j))) {
map.get(wordList.get(i)).add(wordList.get(j));
map.get(wordList.get(j)).add(wordList.get(i));
}
}
}
return map;
}
private static boolean canTransform(String source, String target){
int diffNum=0;
for (int i=0;i<source.length();i++){
if (source.charAt(i)!=target.charAt(i)) {
diffNum++;
}
}
return diffNum==1;
}
}
class WordAndStep{
String word;
int step;
WordAndStep(String word,int step){
this.word=word;
this.step=step;
}
public String getWord() {
return word;
}
public int getStep() {
return step;
}
@Override
public String toString() {
return "WordAndStep{" +
"word='" + word + '\'' +
", step=" + step +
'}';
}
}
总结
- 寻找最小路径这类题需要使用广度优先的方式进行搜索
- 这类最小转换步数,最小路径的问题都可以尝试转换成图后用bfs来求解