Word Search II 解答
Question
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.
Solution
If the current candidate does not exist in all words' prefix, we can stop backtracking immediately. This can be done by using a trie structure.
public class Solution {
Set<String> result = new HashSet<String>();
public List<String> findWords(char[][] board, String[] words) {
Trie trie = new Trie();
for (String word : words)
trie.insert(word);
int m = board.length, n = board[0].length;
boolean[][] visited = new boolean[m][n];
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
dfs(board, "", i, j, trie, visited);
}
}
return new ArrayList<String>(result);
}
private void dfs(char[][] board, String prev, int startX, int startY, Trie trie, boolean[][] visited) {
int m = board.length, n = board[0].length;
if (startX < 0 || startX >= m || startY < 0 || startY >= n)
return;
if (visited[startX][startY])
return;
String current = prev + board[startX][startY];
if (!trie.startsWith(current))
return;
if (trie.search(current))
result.add(current);
visited[startX][startY] = true;
dfs(board, current, startX + 1, startY, trie, visited);
dfs(board, current, startX - 1, startY, trie, visited);
dfs(board, current, startX, startY + 1, trie, visited);
dfs(board, current, startX, startY - 1, trie, visited);
visited[startX][startY] = false;
}
}
Construct Trie
class TrieNode {
public char value;
public boolean isLeaf;
public HashMap<Character, TrieNode> children;
// Initialize your data structure here.
public TrieNode(char c) {
value = c;
children = new HashMap<Character, TrieNode>();
}
}
class Trie {
TrieNode root;
public Trie() {
root = new TrieNode('!');
}
// Inserts a word into the trie.
public void insert(String word) {
char[] wordArray = word.toCharArray();
TrieNode currentNode = root;
for (int i = 0; i < wordArray.length; i++) {
char c = wordArray[i];
HashMap<Character, TrieNode> children = currentNode.children;
TrieNode node;
if (children.containsKey(c)) {
node = children.get(c);
} else {
node = new TrieNode(c);
children.put(c, node);
}
currentNode = node;
if (i == wordArray.length - 1)
currentNode.isLeaf = true;
}
}
// Returns if the word is in the trie.
public boolean search(String word) {
TrieNode currentNode = root;
for (int i = 0; i < word.length(); i++) {
char c = word.charAt(i);
HashMap<Character, TrieNode> children = currentNode.children;
if (children.containsKey(c)) {
TrieNode node = children.get(c);
currentNode = node;
// Need to check whether it's leaf node
if (i == word.length() - 1 && !node.isLeaf)
return false;
} else {
return false;
}
}
return true;
}
// Returns if there is any word in the trie
// that starts with the given prefix.
public boolean startsWith(String prefix) {
TrieNode currentNode = root;
for (int i = 0; i < prefix.length(); i++) {
char c = prefix.charAt(i);
HashMap<Character, TrieNode> children = currentNode.children;
if (children.containsKey(c)) {
TrieNode node = children.get(c);
currentNode = node;
} else {
return false;
}
}
return true;
}
}
Word Search II 解答的更多相关文章
- Leetcode之回溯法专题-212. 单词搜索 II(Word Search II)
Leetcode之回溯法专题-212. 单词搜索 II(Word Search II) 给定一个二维网格 board 和一个字典中的单词列表 words,找出所有同时在二维网格和字典中出现的单词. 单 ...
- 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 ...
- [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 ...
- 212. Word Search II
题目: Given a 2D board and a list of words from the dictionary, find all words in the board. Each word ...
- Word Pattern II 解答
Question Given a pattern and a string str, find if str follows the same pattern. Here follow means a ...
- 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 a 2D board and a list of words from the dictionary, find all words in the board. Each word mus ...
随机推荐
- unix c 03
C程序员的错误处理 errno/perror/strerror 都是系统设计好的 自定义函数中的错误处理 1 可以返回-1 代表错误 2 指针类型可以用 NULL 代表错误 ...
- 软硬结合的可穿戴式app
可穿戴设备已经非常的火热了,各种手环.手表之类的硬件设备已经层出不穷,并且功能也已经越发强大,从简单的运动.心率追踪,到现在的血糖.心电图监测,“量化自我”的愿景似乎已经变得越来越明朗,但也正是在这样 ...
- Integer to English Words 解答
Question Convert a non-negative integer to its english words representation. Given input is guarante ...
- Jquery_Ajax文件上传
如何实现jQuery的Ajax文件上传,PHP如实文件上传.AJAX上传文件,PHP上传文件. [PHP文件上传] 在开始之前,我觉得是有必要把通WEB上传文件的原理简单说一下的.实际上,在这里不管是 ...
- C# yield return 流程理解
代码如下: 在Documents1方法中使用yield return之后, 下次在进入Documents1方法就是从上一次yield return部分执行 using System; using S ...
- 基于google earth engine 云计算平台的全国水体变化研究
第一个博客密码忘记了,今天才来开通第二个博客,时间已经过去两年了,三年的硕士生涯,真的是感慨良多,最有收获的一段时光,莫过于在实验室一个人敲着代码了,研三来得到中科院深圳先进院,在这里开始了新的研究生 ...
- (3)选择元素——(6)属性选择器(Attribute selectors)
Attribute selectors are a particularly helpful subset of CSS selectors. They allow us to specify an ...
- Jquery面试题整合
来自棱镜学院-在线IT教育 www.prismcollege.com 一.Jquery測试题 以下哪种不是jquery的选择器?(单选) A.基本选择器 B.后代选择器 C.类选择器 D.进一 ...
- jquery使用load开展局部刷新没有效果
jquery使用load开展局部刷新没有效果 jquery使用load进行局部刷新没有效果我的代码 <html><head><meta charset="u ...
- mysql 5.6 General error: 1364 Field mysql 严格模式导致
问题:SQLSTATE[HY000]: General error: 1364 Field 解决方法:set global sql-mode=”NO_AUTO_CREATE_USER,NO_ENGIN ...