# 单词接龙
字典 wordList 中从单词 beginWord 和 endWord 的 转换序列 是一个按下述规格形成的序列:
- 序列中第一个单词是
beginWord 。
- 序列中最后一个单词是
endWord 。
- 每次转换只能改变一个字母。
- 转换过程中的中间单词必须是字典
wordList 中的单词。
给你两个单词 beginWord 和 endWord 和一个字典 wordList ,找到从 beginWord 到 endWord 的 最短转换序列 中的 单词数目 。如果不存在这样的转换序列,返回 0。
示例 1:
输入:beginWord = "hit", endWord = "cog", wordList = ["hot","dot","dog","lot","log","cog"]
输出:5
解释:一个最短转换序列是 "hit" -> "hot" -> "dot" -> "dog" -> "cog", 返回它的长度 5。
示例 2:
输入:beginWord = "hit", endWord = "cog", wordList = ["hot","dot","dog","lot","log"]
输出:0
解释:endWord "cog" 不在字典中,所以无法进行转换。
提示:
1 <= beginWord.length <= 10
endWord.length == beginWord.length
1 <= wordList.length <= 5000
wordList[i].length == beginWord.length
beginWord、endWord 和 wordList[i] 由小写英文字母组成
beginWord != endWord
wordList 中的所有字符串 互不相同
## template
```java
public class Solution {
HashMap> mapPositive = new HashMap>();
HashMap> mapNegative = new HashMap>();
HashMap mapVisit = new HashMap();
int result = Integer.MAX_VALUE;
public int ladderLength(String beginWord, String endWord, List wordList) {
for (int i = 0; i < wordList.size(); i++) {
addWordToMap(wordList.get(i));
}
addWordToMap(beginWord);
mapVisit.put(beginWord, true);
findEnd(beginWord, endWord, 1);
if (result == Integer.MAX_VALUE) {
return 0;
}
return result;
}
private void addWordToMap(String word) {
int length = word.length();
if (length == 0) {
return;
}
char[] chars = word.toCharArray();
for (int i = 0; i < length; i++) {
char now = chars[i];
chars[i] = '*';
String regex = new String(chars);
List list;
if (mapPositive.containsKey(word)) {
list = mapPositive.get(word);
} else {
list = new ArrayList();
mapPositive.put(word, list);
}
list.add(regex);
if (mapNegative.containsKey(regex)) {
list = mapNegative.get(regex);
} else {
list = new ArrayList();
mapNegative.put(regex, list);
}
list.add(word);
chars[i] = now;
}
mapVisit.put(word, false);
}
private void findEnd(String nowWord, String endWord, int nowStep) {
if (endWord.equals(nowWord)) {
if (nowStep < result) {
result = nowStep;
}
return;
}
List candidates = getCandidates(nowWord);
if (candidates == null || candidates.size() == 0) {
return;
}
for (int i = 0; i < candidates.size(); i++) {
String now = candidates.get(i);
mapVisit.put(now, true);
findEnd(now, endWord, nowStep + 1);
mapVisit.put(now, false);
}
}
private List getCandidates(String word) {
List list = mapPositive.get(word);
if (list == null) {
return new ArrayList();
}
Set set = new HashSet();
for (int i = 0; i < list.size(); i++) {
String regex = list.get(i);
List regexList = mapNegative.get(regex);
if (regexList == null) {
continue;
}
for (int j = 0; j < regexList.size(); j++) {
String now = regexList.get(j);
if (mapVisit.get(now) == false) {
set.add(now);
}
}
}
List candidates = new ArrayList();
for (String string : set) {
candidates.add(string);
}
return candidates;
}
}
```
## 答案
```java
```
## 选项
### A
```java
```
### B
```java
```
### C
```java
```