[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 ...
随机推荐
- 【前端知识体系-JS相关】深入理解MVVM和VUE
1. v-bind和v-model的区别? v-bind用来绑定数据和属性以及表达式,缩写为':' v-model使用在表单中,实现双向数据绑定的,在表单元素外使用不起作用 2. Vue 中三要素的是 ...
- poj-2935 BFS Basic Wall Maze
Basic Wall Maze Time Limit: 1000MS Memory Limit: 65536K Total Submissions: 3384 Accepted: 1525 ...
- python threading Future源码解析
1. Future内部还是用了condition这个锁 2. Cancel # future在执行时,会一直更新这个状态 def cancel(self): """Can ...
- HTML教程详解
HTML学习笔记 目录 一.html简介 1.html是什么? 2.html能做什么(html的作用)? 3.html书写规范 二.html基本标签 1.标签的语法 2.标签的分类 3.常用标签: 1 ...
- 解决 Visual Studio 符号加载不完全问题
解决 Visual Studio 符号加载不完全问题 工具 - 选项 - 搜索 "符号" - 选上服务器 | 加载所有符号, 之后符号就会显示完全
- 查询SAP系统支持的ABAP版本
7.52可以使用select 内表,但是怎么看版本呢? 如果有在开发中用到ABAP 7.4&7.5个版本的新语法时,需要考虑到系统支持的ABAP版本,那么要怎么查看呢? 其实这个和SAP的内核 ...
- RFC函数的初步使用-同步
1.由于没有外围系统,采用不同SAP不同client之间进行测试. 首先在A-client搭建需要被调用的RFC函数.在A-client里运行SE37创建函数 在属性页签选择“远程启用的模块” 设定i ...
- C# Large Files MD5 C# 获取大文件MD5
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.T ...
- EF操作与Linq写法记录
项目总结:EF操作与Linq写法记录 1.EF引入 新建一个MVC项目之后,要引用EF框架,可以按照以下步骤进行: 1),在Models中添加项目 2),选择Entity Data Model,并重新 ...
- 反射与类对象获取-Java学习
类对象 类对象指的是一个类在jvm中加载后所形成的对象,每一个类都只有一个类对象,该类对象被所有的实例对象所共享. 类之间有不同的方法,不同的属性.类对象,就是用于描述这种类,都有什么属性,什么方法的 ...