Word Ladder 解答
Question
Given two words (beginWord and endWord), and a dictionary's word list, find the length of shortest transformation sequence from beginWord to endWord, such that:
- Only one letter can be changed at a time
- Each intermediate word must exist in the word list
For example,
Given:
beginWord = "hit"
endWord = "cog"
wordList = ["hot","dot","dog","lot","log"]
As one shortest transformation is "hit" -> "hot" -> "dot" -> "dog" -> "cog",
return its length 5.
Note:
- Return 0 if there is no such transformation sequence.
- All words have the same length.
- All words contain only lowercase alphabetic characters.
Solution 1 -- BFS

class WordNode{
String word;
int numSteps;
public WordNode(String word, int numSteps){
this.word = word;
this.numSteps = numSteps;
}
}
public class Solution {
public int ladderLength(String beginWord, String endWord, Set<String> wordList) {
Queue<WordNode> queue = new LinkedList<WordNode>();
queue.add(new WordNode(beginWord, 1));
wordList.add(endWord);
// 由于这里纪录了每个词的最小步数,所以不用两个list
while (queue.size() > 0) {
WordNode topNode = queue.remove();
String current = topNode.word;
if (current.equals(endWord))
return topNode.numSteps;
char[] arr = current.toCharArray();
// 穷举法
for (int i = 0; i < arr.length; i++) {
for (char c = 'a'; c <= 'z'; c++) {
char tmp = arr[i];
if (arr[i] != c)
arr[i] = c;
String newWord = new String(arr);
if (wordList.contains(newWord)) {
queue.add(new WordNode(newWord, topNode.numSteps + 1));
wordList.remove(newWord);
}
arr[i] = tmp;
}
}
}
return 0;
}
}
Solution 2 -- BFS & Adjacency List
Basic idea is: 1. construct adjacency list 2. BFS
Constructing adjacency list uses O(n2) time, and BFS is O(n). Total time complexity is O(n2), when testing in leetcode, it reports "time limit exceeded".
public class Solution {
public int ladderLength(String beginWord, String endWord, Set<String> wordList) {
if (wordList == null)
return -1;
int step = 1;
if (beginWord.equals(endWord))
return 1;
// Construct adjacency lists for words
// Do not forget start word and end word
wordList.add(beginWord);
wordList.add(endWord);
Map<String, List<String>> adjacencyList = new HashMap<String, List<String>>();
Map<String, Boolean> visited = new HashMap<String, Boolean>();
int length = wordList.size();
String[] wordList2 = new String[length];
int i = 0;
for (String current : wordList) {
wordList2[i] = current;
i++;
}
// Initialization
for (i = 0; i < length; i++) {
adjacencyList.put(wordList2[i], new ArrayList<String>());
visited.put(wordList2[i], false);
}
for (i = 0; i < length; i++) {
String current = wordList2[i];
// Construct adjacency list for each element
for (int j = i + 1; j < length; j++) {
String next = wordList2[j];
if (isAdjacent(current, next)) {
List<String> list1 = adjacencyList.get(current);
list1.add(next);
adjacencyList.put(current, list1);
List<String> list2 = adjacencyList.get(next);
list2.add(current);
adjacencyList.put(next, list2);
}
}
}
// BFS
List<String> current = new ArrayList<String>();
List<String> next;
current.add(beginWord);
visited.put(beginWord, true);
while (current.size() > 0) {
step++;
next = new ArrayList<String>();
for (String currentString : current) {
List<String> neighbors = adjacencyList.get(currentString);
if (neighbors == null)
continue;
for (String neighbor : neighbors) {
if (neighbor.equals(endWord))
return step;
if (!visited.get(neighbor)) {
next.add(neighbor);
visited.put(neighbor, true);
}
}
}
current = next;
}
return -1;
}
private boolean isAdjacent(String current, String next) {
if (current.length() != next.length())
return false;
int length = current.length();
int diff = 0;
for (int i = 0; i < length; i++) {
char a = current.charAt(i);
char b = next.charAt(i);
if (a != b)
diff++;
}
if (diff == 1)
return true;
return false;
}
}
Python version
from collections import deque
from collections import defaultdict class Solution:
def ladderLength(self, beginWord: str, endWord: str, wordList: List[str]) -> int:
if endWord not in wordList:
return 0
queue = deque()
queue.append((beginWord, 1))
visited = set([beginWord])
adjacency_map = defaultdict(list)
L = len(beginWord)
# Pre-process
for word in wordList:
for i in range(L):
adjacency_map[word[:i] + "*" + word[i+1:]].append(word)
# BFS
while queue:
curr_word, curr_steps = queue.popleft()
if curr_word == endWord:
return curr_steps
# List all possibilities
for i in range(L):
key = curr_word[:i] + "*" + curr_word[i+1:]
if key in adjacency_map:
neighbors = adjacency_map[key]
for neighbor in neighbors:
if neighbor == endWord:
return curr_steps + 1
if neighbor not in visited:
queue.append((neighbor, curr_steps + 1))
visited.add(neighbor)
adjacency_map[key] = {}
return 0
Word Ladder 解答的更多相关文章
- Word Ladder II 解答
Question Given two words (beginWord and endWord), and a dictionary's word list, find all shortest tr ...
- [LeetCode] Word Ladder 词语阶梯
Given two words (beginWord and endWord), and a dictionary, find the length of shortest transformatio ...
- [LeetCode] Word Ladder II 词语阶梯之二
Given two words (start and end), and a dictionary, find all shortest transformation sequence(s) from ...
- LeetCode:Word Ladder I II
其他LeetCode题目欢迎访问:LeetCode结题报告索引 LeetCode:Word Ladder Given two words (start and end), and a dictiona ...
- 【leetcode】Word Ladder
Word Ladder Total Accepted: 24823 Total Submissions: 135014My Submissions Given two words (start and ...
- 【leetcode】Word Ladder II
Word Ladder II Given two words (start and end), and a dictionary, find all shortest transformation ...
- 18. Word Ladder && Word Ladder II
Word Ladder Given two words (start and end), and a dictionary, find the length of shortest transform ...
- [Leetcode][JAVA] Word Ladder II
Given two words (start and end), and a dictionary, find all shortest transformation sequence(s) from ...
- LeetCode127:Word Ladder II
题目: Given two words (start and end), and a dictionary, find all shortest transformation sequence(s) ...
随机推荐
- POJ3278 Catch That Cow(BFS)
Description Farmer John has been informed of the location of a fugitive cow and wants to catch her i ...
- JUnit三分钟教程 ---- 快速起步
JUnit三分钟教程 ---- 快速起步 摘自http://lavasoft.blog.51cto.com/62575/65625/ JUnit是个好东西,做大点的项目离不开这东西,实际中用的时候也因 ...
- py练习
功能类似pop def myPop(): l=[] a=raw_input('a:') for i in a: l.append(i) l.pop() pr ...
- 字符(汉子)转换为ASCII
一般在jdk里面都会自包含一个官方提供的转换工具:native2ascii.exe 调用方法: 打开cmd界面,使用cd C:\Program Files\Java\jdk1.6.0_39\bin命 ...
- 格而知之16:我所理解的Block(2)
11.那么Block到底是怎么实现的呢?试一试通过将Block 的代码转换成普通C语言代码来查看它的实现过程. 要将OC代码转换成C语言代码,可以使用clang编译的一个命令: 通过这个命令能把指定文 ...
- The account is locked
SQL> select * from v$version where rownum=1; BANNER --------------------------------------------- ...
- Linux进程控制——exec函数族
原文:http://www.cnblogs.com/hnrainll/archive/2011/07/23/2114854.html 1.简介 在Linux中,并不存在exec()函数,exec指的是 ...
- Android开发:shape和selector和layer-list的(详细说明)
http://blog.csdn.net/brokge/article/details/9713041
- Thread was being aborted.你遇到了吗?
这个Exception目前了解到的有两个原因造成: 1.Reponse.Write的问题(目前网上找到的信息十有八九都讲的是这个问题) 2.Web.Config中设定的exec ...
- Java异常基础Exception
异常指不期而至的各种状况,如:文件找不到.网络连接失败.非法参数等.异常是一个事件,它发生在程序运行期间,干扰了正常的指令流程.Java通 过API中Throwable类的众多子类描述各种不同的异常. ...