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

解题思路:

本题承接自Java for LeetCode 079 Word Search 但是用dfs会TLE,真正的做法是将word放进Trie里面,然后遍历trie里的每个点,看是否能匹配到trie里的元素,JAVA实现如下:

public class Solution {
public List<String> findWords(char[][] board, String[] words) {
HashSet<String> list=new HashSet();
Trie trie = new Trie();
for (String word : words)
trie.insert(word);
boolean[][] visited=new boolean[board.length][board[0].length];
for (int i = 0; i < board.length; i++)
for (int j = 0; j < board[0].length; j++)
dfs(list,board, visited, "", i, j, trie);
return new ArrayList(list);
} public void dfs(Set<String> list,char[][] board, boolean[][] visited, String str, int x, int y, Trie trie) {
if (x < 0 || x >= board.length || y < 0 || y >= board[0].length)
return;
if (visited[x][y])
return;
str += board[x][y];
if (!trie.startsWith(str))
return;
if (trie.search(str))
list.add(str);
visited[x][y] = true;
dfs(list,board, visited, str, x - 1, y, trie);
dfs(list,board, visited, str, x + 1, y, trie);
dfs(list,board, visited, str, x, y - 1, trie);
dfs(list,board, visited, str, x, y + 1, trie);
visited[x][y] = false;
}
}
class TrieNode {
// Initialize your data structure here.
int num;// 有多少单词通过这个节点,即节点字符出现的次数
TrieNode[] son;// 所有的儿子节点
boolean isEnd;// 是不是最后一个节点
char val;// 节点的值 TrieNode() {
this.num = 1;
this.son = new TrieNode[26];
this.isEnd = false;
}
} class Trie {
protected TrieNode root; public Trie() {
root = new TrieNode();
} public void insert(String word) {
if (word == null || word.length() == 0)
return;
TrieNode node = this.root;
char[] letters = word.toCharArray();
for (int i = 0; i < word.length(); i++) {
int pos = letters[i] - 'a';
if (node.son[pos] == null) {
node.son[pos] = new TrieNode();
node.son[pos].val = letters[i];
} else {
node.son[pos].num++;
}
node = node.son[pos];
}
node.isEnd = true;
} // Returns if the word is in the trie.
public boolean search(String word) {
if (word == null || word.length() == 0) {
return false;
}
TrieNode node = root;
char[] letters = word.toCharArray();
for (int i = 0; i < word.length(); i++) {
int pos = letters[i] - 'a';
if (node.son[pos] != null) {
node = node.son[pos];
} else {
return false;
}
}
return node.isEnd;
} // Returns if there is any word in the trie
// that starts with the given prefix.
public boolean startsWith(String prefix) {
if (prefix == null || prefix.length() == 0) {
return false;
}
TrieNode node = root;
char[] letters = prefix.toCharArray();
for (int i = 0; i < prefix.length(); i++) {
int pos = letters[i] - 'a';
if (node.son[pos] != null) {
node = node.son[pos];
} else {
return false;
}
}
return true;
}
}

Java for LeetCode 212 Word Search II的更多相关文章

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

  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 、212. Word Search II

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

  5. Java for LeetCode 126 Word Ladder II 【HARD】

    Given two words (start and end), and a dictionary, find all shortest transformation sequence(s) from ...

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

  7. 212. Word Search II

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

  8. Java实现 LeetCode 212 单词搜索 II(二)

    212. 单词搜索 II 给定一个二维网格 board 和一个字典中的单词列表 words,找出所有同时在二维网格和字典中出现的单词. 单词必须按照字母顺序,通过相邻的单元格内的字母构成,其中&quo ...

  9. 【LeetCode】212. Word Search II 解题报告(C++)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 前缀树 日期 题目地址:https://leetco ...

随机推荐

  1. hdu4941 Magical Forest (stl map)

    2014多校7最水的题   Magical Forest Magical Forest Time Limit: 24000/12000 MS (Java/Others)    Memory Limit ...

  2. 由json字符串生成C#实体类的工具

    json作为互联网上轻量便捷的数据传输格式,越来越受到重视.但在服务器端编程过程中,我们常常希望能通过智能提示来提高编码效率.JSON C# Class Generator 能将json格式所表示的J ...

  3. "当前方法的代码已经过优化,无法计算表达式的值"的这个错误的解决方案!!!

    http://blog.useasp.net/archive/2012/09/12/how-to-debug-dotnet-framework-source-when-throw-the-code-o ...

  4. SQL如何将A,B,C替换为'A','B','C'

    因为涉及到逗号,和单引号' 本来想一次转换成功, 但是最后貌似没有好的办法, 只有分两次完成了 select REPLACE(REPLACE('A,B,C',',','>,>'),'> ...

  5. mysql 总结二(自定义存储过程)

    mysql执行流程: sql命令--->mysql引擎-----(分析)---->语法正确-----(编译)--->可识别命令----(执行)---->执行结果---(返回)- ...

  6. VBA 表操作1

    VBA 新建表.批量建表 例1 创建一个工作簿 注意 .name 与 .range ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ...

  7. 浮动层-JS兼容IE6

    //引用jquery 包/*orderBycat 与 orderBycatHead 双层浮动*/ $(window).scroll(function () { var top = $(window). ...

  8. Android-Universal-Image-Loader 图片异步加载类库的使用(超详细配置)

    这个图片异步加载并缓存的类已经被很多开发者所使用,是最常用的几个开源库之一,主流的应用,随便反编译几个火的项目,都可以见到它的身影. 可是有的人并不知道如何去使用这库如何进行配置,网上查到的信息对于刚 ...

  9. sql种类

  10. const 和宏的区别

    参考:http://blog.sina.com.cn/s/blog_79b01f6601018xdg.html (1) 编译器处理方式不同 define宏是在预处理阶段展开. const常量是编译运行 ...