class Solution {
Map<String, Integer> wordId = new HashMap<String, Integer>(); //哈希图,用于广度优先搜索
List<List<Integer>> edge = new ArrayList<List<Integer>>(); //哈希图的邻接表,嵌套的两个一维数组组成的二维数组,
//外层一维数组的每个元素都能映射出一个一维数组用于指明相连接的节点
int nodeNum = 0; //节点数量
public int ladderLength(String beginWord, String endWord, List<String> wordList) { //计算路径长度的主功能函数
for (String word : wordList) {
addEdge(word);
}
addEdge(beginWord);
if (!wordId.containsKey(endWord)) {
return 0;
}
int[] dis = new int[nodeNum];
Arrays.fill(dis, Integer.MAX_VALUE);
int beginId = wordId.get(beginWord), endId = wordId.get(endWord);
dis[beginId] = 0;
Queue<Integer> que = new LinkedList<Integer>();
que.offer(beginId);
while (!que.isEmpty()) {
int x = que.poll();
if (x == endId) {
return dis[endId] / 2 + 1;
}
for (int it : edge.get(x)) {
if (dis[it] == Integer.MAX_VALUE) {
dis[it] = dis[x] + 1;
que.offer(it);
}
}
}
return 0;
}
public void addEdge(String word) { //添加单词相关连结点的函数
addWord(word);
int id1 = wordId.get(word);
char[] array = word.toCharArray();
int length = array.length;
for (int i = 0; i < length; ++i) {
char tmp = array[i];
array[i] = '*';
String newWord = new String(array);
addWord(newWord);
int id2 = wordId.get(newWord);
edge.get(id1).add(id2);
edge.get(id2).add(id1);
array[i] = tmp;
}
}
public void addWord(String word) {
if (!wordId.containsKey(word)) {
wordId.put(word, nodeNum++);
edge.add(new ArrayList<Integer>());
}
}
}
标签:JAVA,String,get,int,单词,接龙,wordId,word,dis
From: https://www.cnblogs.com/Radioactive/p/17787780.html