Input:
beginWord = “hit”,
endWord = “cog”,
wordList = [“hot”,“dot”,“dog”,“lot”,“log”,“cog”]
Output: 5
Explanation: As one shortest transformation is “hit” -> “hot” -> “dot” -> “dog” -> “cog”,
return its length 5.
Input:
beginWord = “hit”
endWord = “cog”
wordList = [“hot”,“dot”,“dog”,“lot”,“log”]
Output: 0
Explanation: The endWord “cog” is not in wordList, therefore no possible transformation.
BFS广度优先搜索,一层一层找
package test;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
public class demo3 {
public static void main(String[] args) {
String beginWord = "hit";
String endWord = "cog";
//String[] list = {"hot","dot","dog","lot","log","cog"};
List<String> list = new ArrayList<>();
list.add("hot");
list.add("dot");
list.add("dog");
list.add("lot");
list.add("log");
list.add("cog");
list.add(beginWord);
int start = list.size()-1;
int end = 0;
while(end<start&&!list.get(end).equals(endWord)) {
end++;
}
if(end==start) {
System.out.println("error");
return;
}
List<Integer>[] graphic = buildGraphic(list);
int step = findShortPath(graphic,start,end);
System.out.println(step);
}
private static List<Integer>[] buildGraphic(List<String> list) {
int n = list.size();
List<Integer>[] graphic = new ArrayList[n];
for(int i=0;i<n;i++) {
List<Integer> subList = new ArrayList<>();
for(int j=0;j<n;j++) {
if(isConnection(list.get(i),list.get(j))) {
subList.add(j);
}
}
graphic[i] = subList;
}
return graphic;
}
private static boolean isConnection(String str1, String str2) {
int count = 0;
int n1 = str1.length();
int n2 = str2.length();
if(n1!=n2) return false;
for(int i=0;i<n1;i++) {
if(str1.charAt(i)!=str2.charAt(i)) {
count++;
}
}
return count==1;
}
private static int findShortPath(List<Integer>[] graphic, int start, int end) {
Queue<Integer> queue = new LinkedList<>();
queue.add(start);
boolean[] marked = new boolean[graphic.length];
marked[start] = true;
int step = 1;
int size = 0;
int cur = 0;
while(!queue.isEmpty()) {
step++;
size = queue.size();
while(size-->0) {
cur = queue.poll();
for(int num:graphic[cur]) {
if(num==end) return step;
if(marked[num]) continue;
queue.add(num);
marked[num] = true;
}
}
}
return 0;
}
}