Description
A transformation sequence from word beginWord to word endWord using a dictionary wordList is a sequence of words beginWord -> s1 -> s2 -> … -> sk such that:
Every adjacent pair of words differs by a single letter.
Every si for 1 <= i <= k is in wordList. Note that beginWord does not need to be in wordList.
sk == endWord
Given two words, beginWord and endWord, and a dictionary wordList, return the number of words in the shortest transformation sequence from beginWord to endWord, or 0 if no such sequence exists.
Examples
Example 1:
Input: beginWord = “hit”, endWord = “cog”, wordList = [“hot”,“dot”,“dog”,“lot”,“log”,“cog”]
Output: 5
Explanation: One shortest transformation sequence is “hit” -> “hot” -> “dot” -> “dog” -> cog", which is 5 words long.
Example 2:
Input: beginWord = “hit”, endWord = “cog”, wordList = [“hot”,“dot”,“dog”,“lot”,“log”]
Output: 0
Explanation: The endWord “cog” is not in wordList, therefore there is no valid transformation sequence.
Constraints:
1 <= beginWord.length <= 10
endWord.length == beginWord.length
1 <= wordList.length <= 5000
wordList[i].length == beginWord.length
beginWord, endWord, and wordList[i] consist of lowercase English letters.
beginWord != endWord
All the words in wordList are unique.
思路
这道题和 433 几乎是一模一样的,用第一种思路构建邻接矩阵,虽然能通过所有case,但由于5000*5000的邻接矩阵过大,最后会报TLE,但是通过word.length * 26个字母的遍历方式,就可以通过测试
另:使用HashSet进行contains判断,会比使用ArrayList进行contains判断要快很多很多很多,后者33/50样例就会TLE
另另:还有一种优化方式是从两头同时进行bi-search,这样可以缩小要检测的范围,代码我没有写,用的是acceptance里面的10ms解法
代码
邻接矩阵
class Solution {
public boolean differOne(String a, String b){
int count = 0;
for (int i = 0; i < a.length(); i++)
if (a.charAt(i) != b.charAt(i))
count ++;
return count == 1;
}
public int ladderLength(String beginWord, String endWord, List<String> wordList) {
if (beginWord.equals(endWord))
return 1;
int[][] matrix = new int[wordList.size()][wordList.size()];
// handle special case
boolean flag = false;
for (String word: wordList){
if (word.equals(endWord)){
flag = true;
break;
}
}
if (!flag)
return 0;
for (int i = 0; i < wordList.size(); i++) {
for (int j = i + 1; j < wordList.size(); j++) {
if (differOne(wordList.get(i), wordList.get(j))){
matrix[i][j] = 1;
matrix[j][i] = 1;
}
}
}
List<Integer> toVisit = new ArrayList<>();
int[] visited = new int[wordList.size()];
int level = 2;
for (int i = 0; i < wordList.size(); i++){
if (differOne(beginWord, wordList.get(i))){
if (wordList.get(i).equals(endWord))
return level;
toVisit.add(i);
visited[i] = 1;
}
}
while (toVisit.size() > 0) {
List<Integer> newVisit = new ArrayList<>();
level ++;
for (int num: toVisit){
for (int i = 0; i < wordList.size(); i++){
if (matrix[i][num] == 1 && visited[i] == 0){
if (wordList.get(i).equals(endWord))
return level;
visited[i] = 1;
newVisit.add(i);
}
}
}
toVisit = new ArrayList<>(newVisit);
}
return 0;
}
}
word.length * 26
class Solution {
public int ladderLength(String beginWord, String endWord, List<String> wordList) {
Set<String> wordDic = new HashSet<>(wordList);
if (!wordDic.contains(endWord))
return 0;
String[] alp = new String[]{"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s","t", "u", "v", "w", "x", "y", "z"};
List<String> toVisit = new ArrayList<>();
Set<String> visited = new HashSet<>();
toVisit.add(beginWord);
int level = 1;
while (toVisit.size() > 0){
level ++;
List<String> newToVisit = new ArrayList<>();
for (String str: toVisit) {
for (int i = 0; i < str.length(); i++) {
for (String a: alp) {
StringBuilder sb = new StringBuilder(str);
sb.replace(i, i + 1, a);
String after = sb.toString();
if (wordDic.contains(after) && !visited.contains(after)){
if (after.equals(endWord))
return level;
newToVisit.add(after);
visited.add(after);
}
}
}
}
toVisit = new ArrayList<>(newToVisit);
}
return 0;
}
}
bi-Search
class Solution {
public int ladderLength(String beginWord, String endWord, List<String> wordList) {
// 第 1 步:先将 wordList 放到哈希表里,便于判断某个单词是否在 wordList 里
Set<String> wordSet = new HashSet<>(wordList);
if (wordSet.size() == 0 || !wordSet.contains(endWord)) {
return 0;
}
// 第 2 步:已经访问过的 word 添加到 visited 哈希表里
Set<String> visited = new HashSet<>();
// 分别用左边和右边扩散的哈希表代替单向 BFS 里的队列,它们在双向 BFS 的过程中交替使用
Set<String> beginVisited = new HashSet<>();
beginVisited.add(beginWord);
Set<String> endVisited = new HashSet<>();
endVisited.add(endWord);
// 第 3 步:执行双向 BFS,左右交替扩散的步数之和为所求
int step = 1;
while (!beginVisited.isEmpty() && !endVisited.isEmpty()) {
// 优先选择小的哈希表进行扩散,考虑到的情况更少
if (beginVisited.size() > endVisited.size()) {
Set<String> temp = beginVisited;
beginVisited = endVisited;
endVisited = temp;
}
// 逻辑到这里,保证 beginVisited 是相对较小的集合,nextLevelVisited 在扩散完成以后,会成为新的 beginVisited
Set<String> nextLevelVisited = new HashSet<>();
for (String word : beginVisited) {
if (changeWordEveryOneLetter(word, endVisited, visited, wordSet, nextLevelVisited)) {
return step + 1;
}
}
// 原来的 beginVisited 废弃,从 nextLevelVisited 开始新的双向 BFS
beginVisited = nextLevelVisited;
step++;
}
return 0;
}
/**
* 尝试对 word 修改每一个字符,看看是不是能落在 endVisited 中,扩展得到的新的 word 添加到 nextLevelVisited 里
*
* @param word
* @param endVisited
* @param visited
* @param wordSet
* @param nextLevelVisited
* @return
*/
private boolean changeWordEveryOneLetter(String word, Set<String> endVisited,
Set<String> visited,
Set<String> wordSet,
Set<String> nextLevelVisited) {
char[] charArray = word.toCharArray();
for (int i = 0; i < word.length(); i++) {
char originChar = charArray[i];
for (char c = 'a'; c <= 'z'; c++) {
// if (originChar == c) {
// continue;
// }
charArray[i] = c;
String nextWord = String.valueOf(charArray);
if (wordSet.contains(nextWord)) {
if (endVisited.contains(nextWord)) {
return true;
}
if (!visited.contains(nextWord)) {
nextLevelVisited.add(nextWord);
visited.add(nextWord);
}
}
}
// 恢复,下次再用
charArray[i] = originChar;
}
return false;
}
}