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. [asp.net core]project.json(1)

    摘要 前面介绍了使用vs2015新建asp.net core web的内容,这篇文章学习下project.json文件的内容. project.json 原文:https://docs.microso ...

  2. _SYS_LIB="-lm -lnsl -ldl"

    -lm  是指连接libm.so     意思是连接数学库, -lnsl  如果涉及RPC编程,必然需要libnsl.so,因此必须在编译选项里加入 -lnsl.      gcc 编译选项 -L是要 ...

  3. 深入理解计算机系统-从书中看到了异或交换ab两个值的新感

    还得从一个很经典的面试题说起:不通过第三个变量来交换两个变量a,b的值... 一个很经典的答案是通过异或来解决: 第壹步:a=a^b; 第贰步:b=a^b; 第叁步:a=a^b; 以前提起" ...

  4. Java并发包源码学习之线程池(一)ThreadPoolExecutor源码分析

    Java中使用线程池技术一般都是使用Executors这个工厂类,它提供了非常简单方法来创建各种类型的线程池: public static ExecutorService newFixedThread ...

  5. 大数据处理时用到maven的repository

    由于做数据处理时,经常遇到maven 下载依赖包错误,下面我将自己下载好的repository 分享下 里边包含:Hadoop ,storm ,sprk ,kafka ,等 压缩后500多M. htt ...

  6. 【PHP面向对象(OOP)编程入门教程】9.封装性(var与public,protected,private的关系)

    封装性是面象对象编程中的三大特性之一,封装性就是把对象的属性和服务结合成一个独立的相同单位,并尽可能隐蔽对象的内部细节,包含两个含义: 1. 把对象的全部属性和全部服务结合在一起,形成一个不可分割的独 ...

  7. VS2010创建动态链接库并且使用动态链接库DLL

    1.编写动态链接库文件 dll和lib文件 例子: 在新建VS工程时选择DLL 空项目 ----------hello.h-------- #include <stdio.h> #prag ...

  8. sass跨文件重写变量

    利用变量默认值: !default 你可以在变量尚未赋值前,通过在值的末尾处添加 !default 标记来为其指定. 也就是说,如果该变量已经被赋值, 就不会再次赋值, 但是,如果还没有被赋值,就会被 ...

  9. ios中二维码的使用之一: 二维码的生成

    iOS在7之后,具备了原生的二维码生成API; 生成二维码的准备:  #import <CoreImage/CoreImage.h> 导入框架: 开始生成: //1- 创建过滤器 CIFi ...

  10. C++和C中的函数如何相互调用

    今天笔试遇到的一题,当时就写了在函数前声明为C,按C编译. 首先是在C中调用C++函数,包括普通函数,重载函数以及成员函数. 对于普通函数,在C++中声明为extern "C",在 ...