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.

Hint:

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.

79. Word Search 的拓展,79题是给一个单词让判断是否存在,现在是给了一堆单词,让返回所有存在的单词。

解法:还是用79题的DFS方法,数据结构用字典树Trie

有关字典树的题还有:208. Implement Trie (Prefix Tree) ,  211. Add and Search Word - Data structure design

Java:

public List<String> findWords(char[][] board, String[] words) {
List<String> res = new ArrayList<>();
TrieNode root = buildTrie(words);
for (int i = 0; i < board.length; i++) {
for (int j = 0; j < board[0].length; j++) {
dfs (board, i, j, root, res);
}
}
return res;
} public void dfs(char[][] board, int i, int j, TrieNode p, List<String> res) {
char c = board[i][j];
if (c == '#' || p.next[c - 'a'] == null) return;
p = p.next[c - 'a'];
if (p.word != null) { // found one
res.add(p.word);
p.word = null; // de-duplicate
} board[i][j] = '#';
if (i > 0) dfs(board, i - 1, j ,p, res);
if (j > 0) dfs(board, i, j - 1, p, res);
if (i < board.length - 1) dfs(board, i + 1, j, p, res);
if (j < board[0].length - 1) dfs(board, i, j + 1, p, res);
board[i][j] = c;
} public TrieNode buildTrie(String[] words) {
TrieNode root = new TrieNode();
for (String w : words) {
TrieNode p = root;
for (char c : w.toCharArray()) {
int i = c - 'a';
if (p.next[i] == null) p.next[i] = new TrieNode();
p = p.next[i];
}
p.word = w;
}
return root;
} class TrieNode {
TrieNode[] next = new TrieNode[26];
String word;
}  

Python:

class TrieNode(object):
# Initialize your data structure here.
def __init__(self):
self.is_string = False
self.leaves = {} # Inserts a word into the trie.
def insert(self, word):
cur = self
for c in word:
if not c in cur.leaves:
cur.leaves[c] = TrieNode()
cur = cur.leaves[c]
cur.is_string = True class Solution(object):
def findWords(self, board, words):
"""
:type board: List[List[str]]
:type words: List[str]
:rtype: List[str]
"""
visited = [[False for j in xrange(len(board[0]))] for i in xrange(len(board))]
result = {}
trie = TrieNode()
for word in words:
trie.insert(word) for i in xrange(len(board)):
for j in xrange(len(board[0])):
if self.findWordsRecu(board, trie, 0, i, j, visited, [], result):
return True return result.keys() def findWordsRecu(self, board, trie, cur, i, j, visited, cur_word, result):
if not trie or i < 0 or i >= len(board) or j < 0 or j >= len(board[0]) or visited[i][j]:
return if board[i][j] not in trie.leaves:
return cur_word.append(board[i][j])
next_node = trie.leaves[board[i][j]]
if next_node.is_string:
result["".join(cur_word)] = True visited[i][j] = True
self.findWordsRecu(board, next_node, cur + 1, i + 1, j, visited, cur_word, result)
self.findWordsRecu(board, next_node, cur + 1, i - 1, j, visited, cur_word, result)
self.findWordsRecu(board, next_node, cur + 1, i, j + 1, visited, cur_word, result)
self.findWordsRecu(board, next_node, cur + 1, i, j - 1, visited, cur_word, result)
visited[i][j] = False
cur_word.pop() 

C++:

class Solution {
public:
struct TrieNode {
TrieNode *child[26];
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[0].empty()) return res;
vector<vector<bool> > visit(board.size(), vector<bool>(board[0].size(), false));
Trie T;
for (auto &a : words) T.insert(a);
for (int i = 0; i < board.size(); ++i) {
for (int j = 0; 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[][2] = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
visit[i][j] = true;
for (auto &a : d) {
int nx = a[0] + i, ny = a[1] + j;
if (nx >= 0 && nx < board.size() && ny >= 0 && ny < board[0].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;
}
};

类似题目:

[LeetCode] 79. Word Search 单词搜索

[LeetCode] 208. Implement Trie (Prefix Tree) 实现字典树(前缀树)

  

All LeetCode Questions List 题目汇总

[LeetCode] 212. Word Search II 词语搜索 II的更多相关文章

  1. 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 ...

  2. [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 ...

  3. [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 ...

  4. LeetCode 79. Word Search(单词搜索)

    Given a 2D board and a word, find if the word exists in the grid. The word can be constructed from l ...

  5. [LeetCode] 79. Word Search 单词搜索

    Given a 2D board and a word, find if the word exists in the grid. The word can be constructed from l ...

  6. leetcode 79. Word Search 、212. Word Search II

    https://www.cnblogs.com/grandyang/p/4332313.html 在一个矩阵中能不能找到string的一条路径 这个题使用的是dfs.但这个题与number of is ...

  7. 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 ...

  8. [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 ...

  9. 【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 ...

随机推荐

  1. C# 上传大文件

    上传大文件首先要修改web.config文件,否则上传报错.在web.config添加如下配置maxRequestLength表示能上传的最大文件值,单位是KB,requestLengthDiskTh ...

  2. JQ js 对数组的操作

    1.数组的创建 var arrayObj = new Array(); //创建一个数组 var arrayObj = new Array([size]); //创建一个数组并指定长度,注意不是上限, ...

  3. vue 弹框

    弹框展示: 代码: <template> <div> <el-col :span="9" style="text-align: right; ...

  4. 【python】json中load和loads区别

    相同点 dump 和 dumps 都实现了序列化 load 和 loads 都实现反序列化 变量从内存中变成可存储或传输的过程称之为序列化序列化是将对象状态转化为可保存或可传输格式的过程. 变量内容从 ...

  5. 2019牛客暑期多校训练营(第三场)G: Removing Stones(启发式分治)

    题意:给定N,表示N堆石子,每堆石子数为a[],问多少个区间,可以满足“石子总和若为偶数,那么可以两两取来自不同堆的石子,直到取完: 如果为奇数,那么排除其中一个,然后可以两两取来自不同堆的石子,直到 ...

  6. LeetCode 837. New 21 Game

    原题链接在这里:https://leetcode.com/problems/new-21-game/ 题目: Alice plays the following game, loosely based ...

  7. IDEA-相关插件使用

    IDEA日常开发中,整理一些用到的插件,以便后续使用起来方便. 点击File-Settings->Plugins. 1.进度条-彩虹,搜索Nyan字样,如图所示(本人已安装),点击Install ...

  8. 洛谷 P3388 【模板】割点(割顶)题解

    今天学了割点,就A了这道板子,比较难理解的地方就在于如果是根节点就要找两个点来满足low[y]>=dfn[x],如果不是就只需找一个点来满足.Tarjan(i,i)中第一个i是开始搜索的点而第 ...

  9. [转载]XML非法字符的处理

    https://blog.csdn.net/qq_36330228/article/details/84779390 static void Main(string[] args) { string ...

  10. 树组件——jstree使用

    本文记录的只是我自己当时的代码,每行的注释很清楚了,你自己可以做相应变通 一.使用前提: 1.下载jstree依赖包 2.相关页面引入样式["jstree/themes/default/st ...