#Problem

#⭐️⭐️⭐️⭐️⭐️

Word Ladder

#Solution

#Solution #1 - Backtracking

简单粗暴就是backtracking, 把所有结果都试出来, 自然能找到最短的. 但是很显然是会超时的.

#Solution #2 - BFS

BFS O(N)就可以搞定. 其实可以看做是一道graph的题.

#Code

#Solution #1 - Backtracking - Java (TLE)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
// Backtracking, TLE
class Solution {
public int ladderLength(String beginWord, String endWord, List<String> wordList) {
final Set<String> dict = new HashSet<>(wordList);
if (!dict.contains(endWord)) return 0;
dict.remove(beginWord);
final Map<String, Integer> dp = new HashMap<>();
ladder(beginWord, endWord, dict, dp);
return dp.get(beginWord);
}
private int ladder(final String beginWord, final String endWord, final Set<String> dict, final Map<String, Integer> dp) {
if (beginWord.equals(endWord)) {
dp.put(beginWord, 1);
return 1;
}
final char[] chs = beginWord.toCharArray();
int res = Integer.MAX_VALUE;
for (int i = 0; i < chs.length; i++) {
for (char c = 'a'; c <= 'z'; c++) {
if (c != chs[i]) {
final char save = chs[i];
chs[i] = c;
final String nextWord = new String(chs);
if (dict.contains(nextWord)) {
dict.remove(nextWord);
int nextRes = ladder(nextWord, endWord, dict, dp);
if (nextRes > 0) {
res = Math.min(res, 1 + nextRes);
}
dict.add(nextWord);
}
chs[i] = save;
}
}
}
res = res == Integer.MAX_VALUE ? 0 : res;
dp.putIfAbsent(beginWord, Integer.MAX_VALUE);
dp.put(beginWord, Math.min(dp.get(beginWord), res));
return res;
}
}
#Solution #2 - BFS - Java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
// BFS
class Solution {
public int ladderLength(String beginWord, String endWord, List<String> wordList) {
final Set<String> dict = new HashSet<>(wordList);
final Set<String> isVisited = new HashSet<>();
final Queue<String> queue = new LinkedList<>();
queue.add(beginWord);
isVisited.add(beginWord);
int depth = 0;
while (!queue.isEmpty()) {
depth++;
final int size = queue.size();
for (int i = 0; i < size; i++) {
final String curr = queue.poll();
if (curr.equals(endWord)) {
return depth;
}
final char[] chs = curr.toCharArray();
for (int k = 0; k < chs.length; k++) {
final char save = chs[k];
for (char c = 'a'; c <= 'z'; c++) {
if (c != save) {
chs[k] = c;
final String nextWord = new String(chs);
if (dict.contains(nextWord) && !isVisited.contains(nextWord)) {
isVisited.add(nextWord);
queue.add(nextWord);
}
}
}
chs[k] = save;
}
}
}
return 0;
}
}

Comments