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. hdu 4504 威威猫系列故事——篮球梦_简单dp

    题目链接 题意:你现在分数为a,对方分数为b,你比赛还有n分钟,每次进攻需要15分钟,现在你先进攻,每次进攻可以得1或2或3,对方每次进攻得一分,问超过对方分数有多少种打法 思路:因为情况太多要用__ ...

  2. 浅谈C++调用C#的DLL程序方法

    把C#编译成DLL或者Axtive控件,再由C调用!比如使用C++调用C#的DLL. SwfDotNet是.net下输出flash的类库.SwfDotNet是C#编写的,作者的C#水平,真是令我佩服. ...

  3. 【转】网络视频监控P2P解决方案

    一.摘要 本文分析了日益增长的民用级别家庭和个人网络视频监控市场的需求特点,并给出了一种经济可行易于大规模部署的P2P解决方案. 由于篇幅有限,本文只给出了方案的思路,未对更深入的技术细节做详细的论述 ...

  4. WPF动画

    System.Windows.Media.Animation 这个命名空间中,包含了三种动画类:线性插值动画类(17个).关键帧动画(22个).路径动画(3个). 线性插值动画类(17个)如下: By ...

  5. 使用Reporting Service订阅对域外用户发邮件

    默认情况下使用Reporting Service对域外邮件发送会失败,一般可能会碰到下面的两个错误: ERROR 1: Subscription Error: "The e-mail add ...

  6. 编程算法 - 圆圈中最后剩下的数字(递推公式) 代码(C++)

    圆圈中最后剩下的数字(递推公式) 代码(C++) 本文地址: http://blog.csdn.net/caroline_wendy 题目: 0,1...,n-1这n个数字排成一个圆圈, 从数字0開始 ...

  7. 谷歌推出情境感知API

    在 Google I/O 2016 大会上,我们宣布推出新的 Google Awareness API,让您的应用可以利用快照和围栏智能应对用户情境,并且仅需占用极少量的系统资源. 所有开发者均可以通 ...

  8. MongoDB学习笔记04

    创建索引使用ensureIndex方法,对于同一个集合,同样的索引只需要创建一次,反复创建是徒劳的. 对某个键的索引会加速对该键的查询,然而,对于其它查询可能没有帮助,即便是查询中包含了被索引的键.实 ...

  9. sketchup 导出 fbx文件 单位 错误

    最近在使用sketchup导出fbx文件到unity中使用时,发生了尺度单位上的错误.按照网上给出的标准教程,选定模型的单位为十进制-米.导出时选项选择'米',但是得到的fbx文件在unity中出现了 ...

  10. 关于css的优先级

    样式的优先级 外部样式 < 内部样式 < 内联样式 选择器的优先权 解释: 1.  内联样式表的权值最高 1000: 2.  ID 选择器的权值为 100; 3.  Class 类选择器的 ...