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. 打开word文档总是自动弹出控件工具条的解决办法:

    打开word文档总是自动弹出控件工具条的解决办法:1.查看是否word文档和模板中了'apmp宏病毒,按ALT+F11组合键,双击当前文档下属的ThisDocument,清空里面的内容:双击Norma ...

  2. 数据库SQL语言学习--上机练习4(视图)

    上机练习4 一.实验目的 . 熟悉和掌握对数据表中视图的查询操作和 SQL 命令的使用: . 熟悉和掌握对数据表中视图的更新操作和 SQL 命令的使用,并注意视图更新与基本表更新的区别与联系: . 学 ...

  3. 方法 - 调试Dll方法

    1.exe加载dll 2.Dll属性设置2.1运行exe生成Debug/...exe2.2属性->调试->命令-> 改成 ./Debug/调试Dll.exe ../Debug/调试D ...

  4. C语言强化——文件

    文件操作 fopen与fclose fread与fwrite fseek fputs与fgets fscanf与fprintf fopen与fclose #include<stdio.h> ...

  5. 利用原生js的Dom操作实现简单的ToDoList的效果

    效果如下: 前端及js代码如下: <!DOCTYPE html> <html lang="en"> <head> <meta charse ...

  6. [UE4]Slot

    一.Slot是容器中子控件的一个属性,因此每个子控件的Slot属性值都可以不一样. 二.不同容器提供的Slot属性都不一样 三.Canvas Panel提供的Slot Anchors预设16种常见的样 ...

  7. video兼容--可用

    兼容ie6,7,8,但是播放器会卡顿黑屏<!DOCTYPE html> <html lang="en"> <head> <meta cha ...

  8. CentOS用户和用户组管理

    groupadd grptest1  按照系统默认的gid创建组.根uid一样,gid也是从1000开始的. groupadd -g 1008 grptest2    创建gid=1008的用户组:g ...

  9. (转)C#SocketAsyncEventArgs实现高效能多并发TCPSocket通信

    原文地址:http://freshflower.iteye.com/blog/2285272.http://freshflower.iteye.com/blog/2285286 一)服务器端 说到So ...

  10. redis 的简单用法

    使用  :下载完后 打开任务管理器 把redis_server 进程关掉, 切换到   E:\redis 中 redis-server.exe redis.windows.conf 打开一个 cmd ...