212. Word Search II
题目:
Given a 2D board and a list of words from the dictionary, find all words in the board.
Each word must be constructed from letters of sequentially adjacent cell, where "adjacent" cells are those horizontally or vertically neighboring. The same letter cell may not be used more than once in a word.
For example,
Given words = ["oath","pea","eat","rain"]
and board =
[
['o','a','a','n'],
['e','t','a','e'],
['i','h','k','r'],
['i','f','l','v']
]
Return ["eat","oath"]
.
Note:
You may assume that all inputs are consist of lowercase letters a-z
.
You would need to optimize your backtracking to pass the larger test. Could you stop backtracking earlier?
If the current candidate does not exist in all words' prefix, you could stop backtracking immediately. What kind of data structure could answer such query efficiently? Does a hash table work? Why or why not? How about a Trie? If you would like to learn how to implement a basic trie, please work on this problem: Implement Trie (Prefix Tree) first.
链接: http://leetcode.com/problems/word-search-ii/
题解:
使用Word Search的方法会超时。因为对每一个word我们都要对整个board进行一遍dfs,所以对于每个单词我们的Time Complexity - O(mn * 26L),大集合的话时间会很长,所以不能用这个方法。
据提示我们尝试使用Tire来做。用words里所有的word先建立好Trie,然后再用DFS扫描board就可以了。为什么我们要使用Trie呢?我觉得主要是因为搜索完一个单词之后,可以继续搜索下一个单词,而不用向Brute force搜索完以后要回头重新查找。举个例子,假如单词为sea,seafood,那么搜索到sea后,我们可以继续搜索seafood。 需要注意的是回溯的时候我们依然要进行剪枝操作。访问过的节点,我们和Word Search一样,先mark为"#",dfs之后再mark回来。搜索到的单词,我们可以把isWord设为false,这样可以处理duplicate。这道题目值得好好理解,整理思路。最近做的一些题目都是动不动就要70+ 行, 希望努力修炼能够有所进步,思维和coding能力。
Time Complexity - O(mn * 26L), Space Complexity - O(26L) <<- 复杂度二刷的时候还要好好分析
public class Solution {
private TrieNode root; private class TrieNode {
private final int R = 26; // Radix R = 26
public boolean isWord;
public TrieNode[] next; public TrieNode() {
next = new TrieNode[R];
}
} public List<String> findWords(char[][] board, String[] words) {
List<String> res = new ArrayList<>();
if(board == null || board.length == 0)
return res;
root = new TrieNode(); for(String word : words) // build Trie
addWords(word); StringBuilder sb = new StringBuilder(); // try assemble word for(int i = 0; i < board.length; i++) {
for(int j = 0; j < board[0].length; j++) {
search(res, sb, root, board, i, j);
}
} return res;
} private void addWords(String word) {
if(word == null || word.length() == 0)
return;
int d = 0;
TrieNode node = root; while(d < word.length()) {
char c = word.charAt(d);
if(node.next[c - 'a'] == null)
node.next[c - 'a'] = new TrieNode();
node = node.next[c - 'a'];
d++;
} node.isWord = true;
} private void search(List<String> res, StringBuilder sb, TrieNode node, char[][] board, int i, int j) {
if(i < 0 || j < 0 || i >= board.length || j >= board[0].length)
return;
if(board[i][j] == '#') // pruning
return;
char c = board[i][j]; TrieNode curRoot = node.next[c - 'a']; // set node here for DFS
if(curRoot == null)
return;
sb.append(c); if(curRoot.isWord == true) {
curRoot.isWord = false;
res.add(sb.toString());
} board[i][j] = '#'; // mark visited cell to '#'
search(res, sb, curRoot, board, i + 1, j);
search(res, sb, curRoot, board, i - 1, j);
search(res, sb, curRoot, board, i, j + 1);
search(res, sb, curRoot, board, i, j - 1);
sb.setLength(sb.length() - 1);
board[i][j] = c; // backtracking
}
}
Reference:
https://leetcode.com/discuss/36411/27-lines-uses-complex-numbers
https://leetcode.com/discuss/36337/my-simple-and-clean-java-code-using-dfs-and-trie
212. Word Search II的更多相关文章
- leetcode 79. Word Search 、212. Word Search II
https://www.cnblogs.com/grandyang/p/4332313.html 在一个矩阵中能不能找到string的一条路径 这个题使用的是dfs.但这个题与number of is ...
- [LeetCode] 212. Word Search II 词语搜索之二
Given a 2D board and a list of words from the dictionary, find all words in the board. Each word mus ...
- 【leetcode】212. Word Search II
Given an m x n board of characters and a list of strings words, return all words on the board. Each ...
- Java for LeetCode 212 Word Search II
Given a 2D board and a list of words from the dictionary, find all words in the board. Each word mus ...
- [LeetCode] 212. Word Search II 词语搜索 II
Given a 2D board and a list of words from the dictionary, find all words in the board. Each word mus ...
- [LeetCode#212]Word Search II
Problem: Given a 2D board and a list of words from the dictionary, find all words in the board. Each ...
- [leetcode trie]212. Word Search II
Given a 2D board and a list of words from the dictionary, find all words in the board. Each word mus ...
- 【LeetCode】212. Word Search II 解题报告(C++)
作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 前缀树 日期 题目地址:https://leetco ...
- 79. 212. Word Search *HARD* -- 字符矩阵中查找单词
79. Word Search Given a 2D board and a word, find if the word exists in the grid. The word can be co ...
随机推荐
- FreeMarker-Built-ins for strings
http://freemarker.org/docs/ref_builtins_string.html Page Contents boolean cap_first capitalize chop_ ...
- 学习C++ Primer 的个人理解(一)
<C++ Primer>这本书可以说是公认的学习C++最好的书,但我觉得不是特别适合作为教材,书中内容的顺序让人有些蛋疼.我个人认为初学此书是不能跳着看的.如果急于上手的话,我更推荐< ...
- how to Enable Client Integration
i got a problem,the problem is list cant use export to excel button in sharepoint 2010. I found my a ...
- 2014-10 u-boot make xxx_defconfig 过程分析
/** ****************************************************************************** * @author Maox ...
- 把div固定在网页顶部
很多网站都有把某一块固定在顶部的功能,今天上网搜搜然后自己又写了一遍,贴出来给大家看看,哪天用到的时候自己也可以随时看看 <!DOCTYPE html PUBLIC "-//W3C// ...
- CURL模拟登陆
index.html <a href="http://adtuu-server.com/login/login.php?auth_username=admin&auth_pas ...
- zencart后台增加菜单选项
如果要在程序中使用额外的参数,在后台控制,添加到菜单属性 在后台 SQL脚本 运行如下 SQL语句 INSERT INTO configuration (configuration_title, co ...
- Delphi代码优化
文章编目 1. 字符串优化 1.1. 不重复初始化 1.2. 使用SetLength预分配长字符串(AnsiString) 1.3. 字符串与动态数组的线程安全(Thread Safety) 1.4. ...
- 小课堂Week8 例外处理设计的逆袭Part1
小课堂Week8 例外处理设计的逆袭Part1 今天和大家讲一本书,书名是<例外处理设计的逆袭>. 为什么想讲这本书,是因为,例外处理在程序代码中到处存在,但是这些到底该如何写好,总觉得有 ...
- what is the purpose of channel coding?(信道编码的作用?)
信道.信道编码及其作用 1.信道(channel) 信道和通信电路并不等同,用来表示向某一个方向传送信息的媒体.因此一条通信线路往往包含一条发送信道和一条接收信道. 从通信的双方信息交互方式看有三个基 ...