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 解答的更多相关文章

  1. Leetcode之回溯法专题-212. 单词搜索 II(Word Search II)

    Leetcode之回溯法专题-212. 单词搜索 II(Word Search II) 给定一个二维网格 board 和一个字典中的单词列表 words,找出所有同时在二维网格和字典中出现的单词. 单 ...

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

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

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

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

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

  6. 212. Word Search II

    题目: Given a 2D board and a list of words from the dictionary, find all words in the board. Each word ...

  7. Word Pattern II 解答

    Question Given a pattern and a string str, find if str follows the same pattern. Here follow means a ...

  8. 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 a 2D board and a list of words from the dictionary, find all words in the board. Each word mus ...

随机推荐

  1. c++ 03

    一.面向对象编程 1.什么是对象?什么是对象编程? 1)万物皆对象 2)世界是由一组相互之间紧密联系的对象组成的. 3)通过将对象按照属性和行为共性进行分类,达到将具体事物进行抽象的效果. 4)通过程 ...

  2. debian下编译libev库

    系统为Linux debian 2.6.32-5-686.这是裸系统,连xwindows都没有.帐户为root,不是的注意一下权限.这里想说明安装过程及出现的问题,故打印的信息较多,以供出现错误的读者 ...

  3. Python 异步IO、IO多路复用

    事件驱动模型 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UT ...

  4. XShell连接CentOS 7.2显示中文乱码问题的解决方法

    背景 使用U盘往Windows主机.Linux主机传文件还是经常的事,但有时候文件名有中文, 传到Linux机器会有乱码,选择起来也很麻烦,最近刚好遇到,写下解决方法. 环境 Linux [root@ ...

  5. Hibernate框架后续

    持久化对象的唯一标识OID 1:我们都知道,在java中按照内存地址来区分同一个类的不同对象        而关系数据库按照主键来区分一条记录 在Hibernate中使用OID来建立内存中的对象和数据 ...

  6. java与.net比较学习系列(4) 运算符和表达式

    上一篇总结了java的数据类型,得到了冰麟轻武等兄弟的支持,他们提出并补充了非常好的建议,在这里向他们表示感谢.在后面的文章中,我会尽力写得更准确和更完善的,加油! 另外,因为C#是在java之后,也 ...

  7. Gstreamer的一些基本概念与A/V同步分析

    一.媒体流(streams )流线程中包含事件和缓存如下:-events     -NEW_SEGMENT    (NS)     -EOS                (EOS)  *     - ...

  8. 《JavaScript 闯关记》之事件

    JavaScript 程序采用了异步事件驱动编程模型.在这种程序设计风格下,当文档.浏览器.元素或与之相关的对象发生某些有趣的事情时,Web 浏览器就会产生事件(event).例如,当 Web 浏览器 ...

  9. css学习之color: window和color: currentColor

    一.易被忽略的属性 color: currentColor color: window   看完之后感觉眼前一亮,有的我之前根本没有用过,甚至都不知道有color: currentColor这么个东西 ...

  10. Javascript中使用replace()方法+正则表达式替换掉所有字符

    Js中的replace方法,只能替换掉第一次匹配到的字符,   而我们经常需要替换一个字符串中所有的匹配字符,这时候可以用正则表达式: str.replace(/a/g,"b"); ...