[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 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:
- All inputs are consist of lowercase letters
a-z
. - 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
类似题目:
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)
LeetCode All in One 题目讲解汇总(持续更新中...)
[LeetCode] 212. Word Search II 词语搜索之二的更多相关文章
- [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] Word Search II 词语搜索之二
Given a 2D board and a list of words from the dictionary, find all words in the board. Each word mus ...
- 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
Problem: Given a 2D board and a list of words from the dictionary, find all words in the board. Each ...
- [LeetCode] 126. Word Ladder II 词语阶梯之二
Given two words (beginWord and endWord), and a dictionary's word list, find all shortest transformat ...
- 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 an m x n board of characters and a list of strings words, return all words on the board. Each ...
- 212. Word Search II
题目: Given a 2D board and a list of words from the dictionary, find all words in the board. Each word ...
- [LeetCode] 126. Word Ladder II 词语阶梯 II
Given two words (beginWord and endWord), and a dictionary's word list, find all shortest transformat ...
随机推荐
- 云原生生态周报 Vol. 15 | K8s 安全审计报告发布
业界要闻 CNCF 公布 Kubernetes 的安全审计报告 报告收集了社区对 Kubernetes.CoreDNS.Envoy.Prometheus 等项目的安全问题反馈,包含从一般弱点到关键漏洞 ...
- Kubernetes service 代理模式
Kubernetes service 代理模式 底层流量转发与负载均衡实现:• Iptables(默认)• IPVS IPVS 了解代理模式之IPVS工作原理LVS 基于 IPVS内核调度模块实现的负 ...
- 『月之谜 数位dp』
月之谜 Description 打败了Lord lsp 之后,由 于lqr 是一个心地善良的女孩 子,她想净化Lord lsp 黑化的 心,使他变回到原来那个天然 呆的lsp--在倒霉的光之英 雄ap ...
- Vue动态修改网页标题
业务需求,进入页面的时候,网页有个默认标题,加载的网页内容不同时,标题需要变更. 例:功能授权,功能授权(张三). Vue下有很多的方式去修改网页标题,这里总结下解决此问题的几种方案: 一.最笨方案 ...
- runtime template in vuejs
在使用vuejs开发的过程中,有时候我们需要动态模板的场景,也就是说模板并不是静态定义好的,而是动态变化的. 比如在做一个所见所得编辑器时,编辑人员可能时刻需要调整他设计的页面内容,而如果页面内容包含 ...
- 一行 Python
很多人学Python,除了它功能强大,简单易学外,代码行数少.语法简洁也是很吸引人的地方.那么,Python的语法到底有多简洁呢?一行Python代码,能实现什么丧心病狂的功能呢? 1.一行代码,实现 ...
- 浅析java线程和OS线程的关系
探究java线程和OS线程之间的联系 一.准备工作 1.查看linux创建线程的方法 man pthread_create 根据man的配置可知,pthread_create会创建一个线程,这个 ...
- 面向对象的六大原则之 单一职责原则——SRP
SRP = Single Responsibility Principle 定义:就一个类而言,应该只有一个能引起他变化的原因.通俗的说,即一个类只负责一项职责. 作用: 1.减少了类之间的耦 ...
- 使用highcharts实现无其他信息纯趋势图实战实例
使用highcharts实现无其他信息纯趋势图实战实例 Highcharts去掉或者隐藏掉y轴的刻度线yAxis : { gridLineWidth: 0, labels:{ //enabled:fa ...
- Scrum 之 product Backlog
转载:http://www.zhoujingen.cn/blog/2767.html Scrum的基本概念其实并不复杂,但是想做好并不容易,大家都知道product backlog的重要性,但是我们如 ...