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.

Example:

Input:
board = [
['o','a','a','n'],
['e','t','a','e'],
['i','h','k','r'],
['i','f','l','v']
]
words = ["oath","pea","eat","rain"] Output: ["eat","oath"]

Note:

  1. All inputs are consist of lowercase letters a-z.
  2. The values of words are distinct.

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.

这道题是在之前那道 Word Search 的基础上做了些拓展,之前是给一个单词让判断是否存在,现在是给了一堆单词,让返回所有存在的单词,在这道题最开始更新的几个小时内,用 brute force 是可以通过 OJ 的,就是在之前那题的基础上多加一个 for 循环而已,但是后来出题者其实是想考察字典树的应用,所以加了一个超大的 test case,以至于 brute force 无法通过,强制我们必须要用字典树来求解。LeetCode 中有关字典树的题还有 Implement Trie (Prefix Tree) 和 Add and Search Word - Data structure design,那么我们在这题中只要实现字典树中的 insert 功能就行了,查找单词和前缀就没有必要了,然后 DFS 的思路跟之前那道 Word Search 基本相同,请参见代码如下:

class Solution {
public:
struct TrieNode {
TrieNode *child[];
string str;
TrieNode() : str("") {
for (auto &a : child) a = NULL;
}
};
struct Trie {
TrieNode *root;
Trie() : root(new TrieNode()) {}
void insert(string s) {
TrieNode *p = root;
for (auto &a : s) {
int i = a - 'a';
if (!p->child[i]) p->child[i] = new TrieNode();
p = p->child[i];
}
p->str = s;
}
};
vector<string> findWords(vector<vector<char>>& board, vector<string>& words) {
vector<string> res;
if (words.empty() || board.empty() || board[].empty()) return res;
vector<vector<bool>> visit(board.size(), vector<bool>(board[].size(), false));
Trie T;
for (auto &a : words) T.insert(a);
for (int i = ; i < board.size(); ++i) {
for (int j = ; j < board[i].size(); ++j) {
if (T.root->child[board[i][j] - 'a']) {
search(board, T.root->child[board[i][j] - 'a'], i, j, visit, res);
}
}
}
return res;
}
void search(vector<vector<char>>& board, TrieNode* p, int i, int j, vector<vector<bool>>& visit, vector<string>& res) {
if (!p->str.empty()) {
res.push_back(p->str);
p->str.clear();
}
int d[][] = {{-, }, {, }, {, -}, {, }};
visit[i][j] = true;
for (auto &a : d) {
int nx = a[] + i, ny = a[] + j;
if (nx >= && nx < board.size() && ny >= && ny < board[].size() && !visit[nx][ny] && p->child[board[nx][ny] - 'a']) {
search(board, p->child[board[nx][ny] - 'a'], nx, ny, visit, res);
}
}
visit[i][j] = false;
}
};

Github 同步地址:

https://github.com/grandyang/leetcode/issues/212

类似题目:

Word Search

Unique Paths III

参考资料:

https://leetcode.com/problems/word-search-ii/

https://leetcode.com/problems/word-search-ii/discuss/59780/Java-15ms-Easiest-Solution-(100.00)

https://leetcode.com/problems/word-search-ii/discuss/59784/My-simple-and-clean-Java-code-using-DFS-and-Trie

LeetCode All in One 题目讲解汇总(持续更新中...)

最新文章

  1. 一次ie8模式下click无反应的小事
  2. MySQL导入sql脚本错误:2006 - MySQL server has gone away
  3. [Bootstrap]7天深入Bootstrap(1)入门准备
  4. Winform调用百度地图接口
  5. ASP.net中网站访问量统计方法代码(在线人数,本月访问,本日访问,访问流量,累计访问)
  6. python自学笔记一
  7. CXF(2.7.10) - WSDL2Java generated Client
  8. PAT (Advanced Level) 1002. A+B for Polynomials (25)
  9. 闲来无事研究一下酷狗缓存文件kgtemp的加密方式
  10. Windows7安装Pygame软件
  11. 搭建微服务器:express+https+api代理
  12. GO语言学习笔记(一)
  13. fwrite文件写入数据
  14. jabRef里引用的相邻同名作者变横线
  15. C#串口通信遇到的坑
  16. ABP框架系列之一:(Entity-实体)
  17. 【JAVA WEB教程】jsp环境搭建+部署网站(eclipse+tomcat)【详细+图文】
  18. 【AGC005F】Many Easy Problems
  19. Django后端项目---- rest framework(3)
  20. 排错-Ad&#160;Hoc&#160;Distributed&#160;Queries组件被禁用的解决办法

热门文章

  1. python合并视频
  2. Algorithm: CRT、EX-CRT &amp; Lucas、Ex-Lucas
  3. Vue.js 源码分析(二) 基础篇 全局配置
  4. Spring @CrossOrigin 通配符 解决跨域问题
  5. VS2013(InstallShield2015LimitedEdition)打包程序详解
  6. 一张图搞定 .NET Framework, .NET Core 和 .NET Standard 的区别
  7. js-深拷贝浅拷贝
  8. block注意事项
  9. 读《TCP/IP详解》:TCP
  10. python从入门到放弃之进程锁lock