class Solution {
public List<String> findWords(char[][] board, String[] words) {
List<String> res = new ArrayList<>();
TrieNode root = buildTrie(words);
for (int i = 0; i < board.length; i++) {
for (int j = 0; j < board[0].length; j++) {
dfs (board, i, j, root, res);
}
}
return res;
} public void dfs(char[][] board, int i, int j, TrieNode p, List<String> res) {
char c = board[i][j];
if (c == '#' || p.next[c - 'a'] == null) return;
p = p.next[c - 'a'];
if (p.word != null) { // found one
res.add(p.word);
p.word = null; // de-duplicate
} board[i][j] = '#';
if (i > 0) dfs(board, i - 1, j ,p, res);
if (j > 0) dfs(board, i, j - 1, p, res);
if (i < board.length - 1) dfs(board, i + 1, j, p, res);
if (j < board[0].length - 1) dfs(board, i, j + 1, p, res);
board[i][j] = c;
} public TrieNode buildTrie(String[] words) {
TrieNode root = new TrieNode();
for (String w : words) {
TrieNode p = root;
for (char c : w.toCharArray()) {
int i = c - 'a';
if (p.next[i] == null) p.next[i] = new TrieNode();
p = p.next[i];
}
p.word = w;
}
return root;
} class TrieNode {
TrieNode[] next = new TrieNode[26];
String word;
}
}

参考:https://leetcode.com/problems/word-search-ii/discuss/59780/Java-15ms-Easiest-Solution-(100.00)

leetcode212的更多相关文章

  1. [Swift]LeetCode212. 单词搜索 II | Word Search II

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

  2. LeetCode212. Word Search II

    https://leetcode.com/problems/word-search-ii/description/ Given a 2D board and a list of words from ...

随机推荐

  1. java线程之间的通信

    1.常用的方法 sleep() 该线程进入等待状态,不释放锁 wait() 该线程进入等待状态,释放锁 notify() 随机唤醒一个线程 notifyAll() 唤醒全部线程 getName() 获 ...

  2. VMWare VSphere6.0的实验笔记

    在现有的一个vsphere6.0虚拟平台上环境下搭建一套VSphere环境平台. 任务1: 1.建立1个win2008主机,192.168.12.10.16Gram,40G硬盘1独立存储+150G硬盘 ...

  3. googletest基本测试宏

    还不知道googletest基本使用方法的请参看前一篇blog  使用googletest进行C++单元测试 本篇仍然使用testStack测试文件进行测试,测试代码如下 #include <g ...

  4. Android WebView 开发详解

    Android WebView 开发详解 参见 http://blog.csdn.net/typename/article/details/39030091

  5. P2837晚餐队列安排

    传送 特写此篇,纪念不用dp做dp题 洛谷说这是个dp,但我不信(其实就是不会dp),因此我们考虑用另一种思路.修改后的队列每一个 数a[i]一定满足a[i]<=a[i+1],那修改后的顺序就是 ...

  6. Web jsp开发学习——实现页面跳转和传参

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletExcepti ...

  7. dropwizard使用cors支持跨域浏览器取不到自定义header问题

    dropwizard支持cors的配置如下: public void run(Configuration conf, Environment environment) { // Enable CORS ...

  8. intent--Activity之间数据传递之Intent数据传递

    intent传值: 4,intent传集合 3,intent传对象, 2,传递后有返回值的情况:当需要从目标Activity回传数据到原Activity时,可以使用上述方法定义一个新的Intent来传 ...

  9. Java笔试面试题整理第一波

    转载至:http://blog.csdn.net/shakespeare001/article/details/51151650 作者:山代王(开心阳) 本系列整理Java相关的笔试面试知识点,其他几 ...

  10. Docker使用札记 - 使用中遇到的问题总结

    1. 启动容器时报错误“: No such file or directory” 一般来说作为容器应用的入口都是entrypoint.sh文件,也就是Dockerfile最后一条指令为是: ENTRY ...